// app.jsx — main App: auth → role select → role-based shell

const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA, useRef: useRefA } = React;

// ─── Auth / sign in screen ────────────────────────────────────
function AuthScreen({ onAuth, onSignUp, lang, setLang }) {
  const t = T[lang];
  const L = lang === 'th'
    ? {
        welcome: 'ยินดีต้อนรับ',
        sub: 'เข้าสู่ระบบเพื่อใช้งาน Bodin plus',
        id: 'รหัสประจำตัว',
        idPlaceholder: 'นักเรียน: เลขประจำตัว · ครู: รหัสบุคลากร',
        pw: 'รหัสผ่าน',
        pwPlaceholder: 'รหัสผ่านของคุณ',
        remember: 'จดจำฉันไว้',
        forgot: 'ลืมรหัสผ่าน?',
        signin: 'เข้าสู่ระบบ',
        or: 'หรือเข้าสู่ระบบด้วย',
        sso: 'Microsoft 365 ของโรงเรียน',
        google: 'บัญชี Google',
        help: 'ต้องการความช่วยเหลือ? ติดต่อแอดมิน',
        demo: 'โหมดสาธิต · ตัวเลขล้วน = นักเรียน · อักษร = ครู',
        version: 'เวอร์ชัน 1.2 · ปีการศึกษา 2569',
        showPw: 'แสดงรหัสผ่าน',
        invalid: 'กรุณากรอกรหัสประจำตัวและรหัสผ่าน',
      }
    : {
        welcome: 'Welcome back',
        sub: 'Sign in to continue to Bodin plus',
        id: 'Account ID',
        idPlaceholder: 'Student / staff ID',
        pw: 'Password',
        pwPlaceholder: 'Your password',
        remember: 'Remember me',
        forgot: 'Forgot password?',
        signin: 'Sign in',
        or: 'Or continue with',
        sso: 'School Microsoft 365',
        google: 'Google account',
        help: 'Need help? Contact admin',
        demo: 'Demo · digits = student, letters = teacher',
        version: 'v1.2 · Academic year 2026',
        showPw: 'Show password',
        invalid: 'Please enter your ID and password',
      };

  const [id, setId] = useStateA(() => {
    try { return localStorage.getItem('bp_remember_id') || ''; }
    catch { return ''; }
  });
  const [pw, setPw] = useStateA('');
  const [showPw, setShowPw] = useStateA(false);
  const [remember, setRemember] = useStateA(() => {
    try { return localStorage.getItem('bp_remember_id') ? true : true; }
    catch { return true; }
  });
  const [submitting, setSubmitting] = useStateA(false);
  const [err, setErr] = useStateA('');

  function detectRole(id) {
    const v = (id || '').trim();
    // Numeric-only IDs (student ID format) → student
    if (/^\d+$/.test(v)) return 'student';
    // student.* email → student
    if (/^[^@\s]+@student\./i.test(v)) return 'student';
    // anything else (alphanum, staff email, teacher ID with prefix) → teacher
    return 'teacher';
  }

  async function submit(e) {
    e?.preventDefault?.();
    if (!id.trim() || !pw.trim()) { setErr(L.invalid); return; }
    setErr('');
    setSubmitting(true);
    try {
      if (SB_CONFIGURED) {
        const { user, profile } = await sbSignIn(id.trim(), pw);
        setSubmitting(false);
        try {
          if (remember) localStorage.setItem('bp_remember_id', id.trim());
          else localStorage.removeItem('bp_remember_id');
        } catch {}
        onAuth({
          id: id.trim(), remember,
          role: profile?.role || detectRole(id.trim()),
          userId: user.id,
          displayName: profile?.display_name,
          grade: profile?.grade,
          avatarUrl: profile?.avatar_url,
        });
      } else {
        await new Promise(r => setTimeout(r, 650));
        setSubmitting(false);
        try {
          if (remember) localStorage.setItem('bp_remember_id', id.trim());
          else localStorage.removeItem('bp_remember_id');
        } catch {}
        onAuth({ id: id.trim(), remember, role: detectRole(id.trim()) });
      }
    } catch (sbErr) {
      setSubmitting(false);
      setErr(lang === 'th' ? 'รหัสผ่านหรือรหัสประจำตัวไม่ถูกต้อง' : 'Invalid ID or password');
    }
  }

  return (
    <div style={{
      minHeight: '100vh',
      display:'flex', alignItems:'center', justifyContent:'center',
      padding: 24, position: 'relative', overflow:'hidden',
      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%),
        radial-gradient(45% 40% at 100% 90%, oklch(0.68 0.18 220 / 0.20) 0%, transparent 60%),
        var(--bp-canvas)
      `,
    }}>
      {/* Crest watermark (school emblem) */}
      <img src="assets/bodin-crest.jpg" alt="" aria-hidden="true" style={{
        position:'absolute', right:'-6%', bottom:'-12%',
        width: 'min(620px, 70vw)', maxWidth:'none',
        opacity: 0.06, pointerEvents:'none',
        mixBlendMode: 'multiply',
        filter:'saturate(1.1)',
        transform:'rotate(-6deg)',
        borderRadius: 24,
      }}/>

      {/* Top-right lang */}
      <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)',
        boxShadow:'var(--bp-shadow-sm)',
      }}>
        {['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>

      {/* Two-column composition: brand side + form card */}
      <div className="bp-login-grid" style={{
        width:'100%', maxWidth: 1040, alignItems:'center',
      }}>
        {/* LEFT — brand */}
        <div style={{ display:'flex', flexDirection:'column', gap: 28, minWidth: 0, position:'relative' }}>
          <div style={{ display:'inline-flex', alignItems:'center', gap: 14 }}>
            <div style={{
              width: 60, height: 60, borderRadius: 16, overflow:'hidden',
              boxShadow:'0 8px 22px rgba(31, 60, 150, 0.35), 0 0 0 1px rgba(45,30,110,0.06)',
              flexShrink: 0,
            }}>
              <img src="assets/bodin-crest.jpg" alt="ตราโรงเรียนบดินทรเดชา" style={{
                width:'100%', height:'100%', objectFit:'cover', display:'block',
              }}/>
            </div>
            <div>
              <div style={{ fontFamily:'Space Grotesk', fontSize: 24, fontWeight: 600, letterSpacing:'-0.02em' }}>Bodin plus</div>
              <div style={{ fontSize: 12, color:'var(--bp-ink-3)', marginTop: 2 }}>{t.schoolName}</div>
            </div>
          </div>

          <div>
            <h1 style={{
              margin: 0, fontSize: 'clamp(34px, 4.4vw, 50px)', fontWeight: 700,
              letterSpacing:'-0.025em', lineHeight: 1.05,
              background:'var(--bp-grad)',
              WebkitBackgroundClip:'text', backgroundClip:'text', color:'transparent',
            }}>
              {lang === 'th' ? 'ร่วมสร้างโรงเรียน\nที่น่าอยู่ขึ้น' : 'Help us make\nour school better'}
            </h1>
            <p style={{ margin:'14px 0 0', fontSize: 15, color:'var(--bp-ink-2)', maxWidth: 460, lineHeight: 1.6 }}>
              {lang === 'th'
                ? 'แจ้งปัญหาภายในโรงเรียนได้ในไม่กี่วินาที — ติดตามสถานะ ดูภาพหลังแก้ไข และไทม์ไลน์ทุกขั้นตอน'
                : 'Report school issues in seconds — track status, see after-photos, and follow every step.'}
            </p>
          </div>

          {/* small stat row */}
        </div>

        {/* RIGHT — form card */}
        <div style={{
          background:'rgba(255,255,255,0.92)',
          backdropFilter:'blur(24px) saturate(180%)',
          WebkitBackdropFilter:'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)',
        }}>
          <div style={{ fontSize: 22, fontWeight: 700, color:'var(--bp-ink)', letterSpacing:'-0.01em' }}>{L.welcome}</div>
          <div style={{ fontSize: 13, color:'var(--bp-ink-3)', marginTop: 4 }}>{L.sub}</div>

          <form onSubmit={submit} style={{ marginTop: 22, display:'flex', flexDirection:'column', gap: 14 }}>
            <FieldGroup label={L.id} icon="user">
              <input value={id} onChange={e => setId(e.target.value)}
                placeholder={L.idPlaceholder}
                autoComplete="username"
                style={authInputStyle}/>
            </FieldGroup>

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

            {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>
            )}

            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop: 2 }}>
              <label style={{ display:'flex', alignItems:'center', gap: 8, fontSize: 12.5, color:'var(--bp-ink-2)', cursor:'pointer' }}>
                <span onClick={(e) => { e.preventDefault(); setRemember(r => !r); }} style={{
                  width: 18, height: 18, borderRadius: 5,
                  border: remember ? '0' : '1.5px solid var(--bp-line-2)',
                  background: remember ? 'var(--bp-grad)' : '#fff',
                  display:'inline-flex', alignItems:'center', justifyContent:'center',
                  color:'#fff', transition:'background .15s ease',
                }}>
                  {remember && <Icon name="check" size={12} strokeWidth={2.6}/>}
                </span>
                <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)} style={{ display:'none' }}/>
                {L.remember}
              </label>
            </div>

            <button type="submit" disabled={submitting} style={{
              marginTop: 6, 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/> {lang === 'th' ? 'กำลังเข้าสู่ระบบ...' : 'Signing in…'}</>
                : <>{L.signin} <Icon name="arrow_r" size={16}/></>}
            </button>
          </form>

          <div style={{
            marginTop: 20, paddingTop: 16, borderTop:'1px solid var(--bp-line)',
            display:'flex', alignItems:'center', justifyContent:'space-between',
            fontSize: 11.5, color:'var(--bp-ink-3)',
          }}>
            <span>
              {lang === 'th' ? 'ยังไม่มีบัญชี? ' : "Don't have an account? "}
              <button onClick={onSignUp} style={{
                appearance:'none', border:0, background:'transparent', cursor:'pointer',
                color:'var(--bp-blue)', fontSize: 12, fontWeight: 600, padding: 0,
              }}>
                {lang === 'th' ? 'ลงทะเบียนนักเรียนใหม่' : 'Sign up'} ›
              </button>
            </span>
            <span>{L.version}</span>
          </div>

        </div>
      </div>
    </div>
  );
}

function FieldGroup({ label, icon, trailing, children }) {
  return (
    <div>
      <div style={{ fontSize: 12, fontWeight: 600, color:'var(--bp-ink-2)', marginBottom: 6 }}>{label}</div>
      <div style={{
        display:'flex', alignItems:'center', gap: 10,
        padding:'2px 12px', borderRadius: 12,
        border:'1px solid var(--bp-line)',
        background:'#fff',
        transition:'border-color .15s ease, box-shadow .15s ease',
      }}
      onFocus={() => {}}>
        <Icon name={icon} size={16} stroke="var(--bp-ink-3)"/>
        <div style={{ flex: 1, display:'flex' }}>{children}</div>
        {trailing}
      </div>
    </div>
  );
}

const authInputStyle = {
  width:'100%', appearance:'none', border:0, background:'transparent',
  outline:'none', fontFamily:'inherit', fontSize: 14, color:'var(--bp-ink)',
  padding:'12px 0',
};

function SSOButton({ label, kind, onClick }) {
  const logo = kind === 'microsoft' ? (
    <svg width="16" height="16" viewBox="0 0 16 16">
      <rect x="0.5" y="0.5" width="7" height="7" fill="#F25022"/>
      <rect x="8.5" y="0.5" width="7" height="7" fill="#7FBA00"/>
      <rect x="0.5" y="8.5" width="7" height="7" fill="#00A4EF"/>
      <rect x="8.5" y="8.5" width="7" height="7" fill="#FFB900"/>
    </svg>
  ) : (
    <svg width="16" height="16" viewBox="0 0 16 16">
      <path d="M15.7 8.18c0-.55-.05-1.08-.14-1.59H8v3.01h4.32a3.7 3.7 0 0 1-1.6 2.43v2.02h2.6c1.51-1.4 2.38-3.45 2.38-5.87z" fill="#4285F4"/>
      <path d="M8 16c2.16 0 3.97-.72 5.3-1.95l-2.6-2.02c-.72.48-1.64.77-2.7.77-2.07 0-3.83-1.4-4.46-3.28h-2.7v2.07A8 8 0 0 0 8 16z" fill="#34A853"/>
      <path d="M3.54 9.52A4.8 4.8 0 0 1 3.27 8c0-.53.09-1.04.27-1.52V4.41H.84A8 8 0 0 0 0 8c0 1.29.31 2.51.84 3.59l2.7-2.07z" fill="#FBBC05"/>
      <path d="M8 3.18c1.17 0 2.22.4 3.05 1.2l2.29-2.29A8 8 0 0 0 8 0 8 8 0 0 0 .84 4.41l2.7 2.07C4.17 4.58 5.93 3.18 8 3.18z" fill="#EA4335"/>
    </svg>
  );
  return (
    <button type="button" onClick={onClick} style={{
      appearance:'none', cursor:'pointer',
      padding:'12px 14px', borderRadius: 12,
      background:'#fff', border:'1px solid var(--bp-line)',
      fontSize: 13, fontWeight: 500, color:'var(--bp-ink-2)',
      display:'flex', alignItems:'center', gap: 12,
      transition:'border-color .15s ease, background .15s ease',
    }}>
      {logo}
      <span style={{ flex: 1, textAlign:'left' }}>{label}</span>
      <Icon name="arrow_r" size={14} stroke="var(--bp-ink-3)"/>
    </button>
  );
}

function Spinner() {
  return (
    <span style={{
      width: 14, height: 14, borderRadius:'50%',
      border:'2px solid rgba(255,255,255,0.4)', borderTopColor:'#fff',
      animation:'bp-spin 0.7s linear infinite', display:'inline-block',
    }}/>
  );
}

// ─── Role-picker screen ──────────────────────────────────────
function LoginScreen({ onSelect, lang, setLang, onLogout, signedInAs }) {
  const t = T[lang];
  const [hover, setHover] = useStateA(null);

  return (
    <div style={{
      minHeight: '100vh',
      display:'flex', alignItems:'center', justifyContent:'center',
      padding: 24, position: 'relative',
      background: `
        radial-gradient(80% 60% at 80% 0%,  oklch(0.72 0.18 305 / 0.35) 0%, transparent 60%),
        radial-gradient(60% 50% at 0% 100%, oklch(0.65 0.20 250 / 0.30) 0%, transparent 60%),
        radial-gradient(50% 40% at 100% 80%, oklch(0.70 0.20 230 / 0.20) 0%, transparent 60%),
        var(--bp-canvas)
      `,
    }}>
      {/* Lang toggle, top-right */}
      <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)',
        boxShadow:'var(--bp-shadow-sm)',
      }}>
        {['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>

      {/* Signed-in chip, top-left */}
      {signedInAs && (
        <div style={{ position:'absolute', top: 22, left: 22,
          display:'flex', alignItems:'center', gap: 8,
          background:'rgba(255,255,255,0.78)',
          backdropFilter:'blur(20px) saturate(180%)',
          border:'1px solid rgba(255,255,255,0.7)',
          borderRadius: 999, padding:'4px 6px 4px 14px',
          boxShadow:'var(--bp-shadow-sm)',
          fontSize: 12,
        }}>
          <span style={{ width: 7, height: 7, borderRadius:'50%', background:'oklch(0.65 0.16 155)' }}/>
          <span style={{ color:'var(--bp-ink-2)' }}>
            {lang === 'th' ? 'เข้าสู่ระบบในชื่อ' : 'Signed in as'} <strong style={{ color:'var(--bp-ink)' }}>{signedInAs}</strong>
          </span>
          <button onClick={onLogout} title={lang === 'th' ? 'ออกจากระบบ' : 'Sign out'} style={{
            appearance:'none', border:0, cursor:'pointer',
            width: 28, height: 28, borderRadius:'50%',
            background:'var(--bp-soft)', color:'var(--bp-ink-2)',
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <Icon name="logout" size={13}/>
          </button>
        </div>
      )}

      <div style={{ maxWidth: 920, width:'100%', textAlign: 'center', display:'flex', flexDirection:'column', alignItems:'center', gap: 36 }}>
        {/* brand mark */}
        <div style={{ display:'inline-flex', alignItems:'center', gap: 12 }}>
          <Logomark size={56}/>
          <div style={{ textAlign:'left' }}>
            <div style={{ fontFamily:'Space Grotesk', fontSize: 28, fontWeight: 600, letterSpacing:'-0.02em' }}>Bodin plus</div>
            <div style={{ fontSize: 12, color:'var(--bp-ink-3)', marginTop: 2 }}>{t.schoolName}</div>
          </div>
        </div>

        <div>
          <h1 style={{
            margin: 0, fontSize: 'clamp(34px, 5vw, 52px)', fontWeight: 700,
            letterSpacing:'-0.025em', lineHeight: 1.05,
            background:'var(--bp-grad)',
            WebkitBackgroundClip:'text', backgroundClip:'text',
            color:'transparent',
          }}>
            {t.chooseRole}
          </h1>
          <p style={{ margin:'14px auto 0', fontSize: 15, color:'var(--bp-ink-2)', maxWidth: 520, lineHeight: 1.6 }}>
            {t.chooseRoleSub}
          </p>
        </div>

        {/* role cards */}
        <div className="bp-role-grid" style={{ width:'100%', maxWidth: 720 }}>
          <RoleCard
            role="student" t={t}
            tint="oklch(0.58 0.20 250)"
            grad="linear-gradient(135deg, oklch(0.55 0.20 240), oklch(0.60 0.18 220))"
            title={t.student} subtitle={t.studentSub}
            icon="user"
            features={lang === 'th'
              ? ['ถ่ายภาพและส่งเรื่อง', 'ติดตามสถานะการแก้ไข', 'รับคะแนนพลเมืองดี']
              : ['Snap & submit', 'Track progress', 'Earn good-citizen points']}
            hover={hover === 'student'}
            onHover={() => setHover('student')}
            onLeave={() => setHover(null)}
            onClick={() => onSelect('student')}
          />
          <RoleCard
            role="teacher" t={t}
            tint="oklch(0.56 0.24 295)"
            grad="linear-gradient(135deg, oklch(0.50 0.22 285), oklch(0.58 0.22 320))"
            title={t.teacher} subtitle={t.teacherSub}
            icon="layout"
            features={lang === 'th'
              ? ['แดชบอร์ดสรุปทั้งโรงเรียน', 'อัปโหลดภาพหลังแก้ไข', 'ส่งคำขอบคุณนักเรียน']
              : ['School-wide dashboard', 'Upload after-photos', 'Send thanks to students']}
            hover={hover === 'teacher'}
            onHover={() => setHover('teacher')}
            onLeave={() => setHover(null)}
            onClick={() => onSelect('teacher')}
          />
        </div>

        <div style={{ fontSize: 11, color:'var(--bp-ink-3)', display:'flex', alignItems:'center', gap: 6 }}>
          <span style={{ width: 5, height: 5, borderRadius:'50%', background:'oklch(0.65 0.16 155)' }}/>
          {lang === 'th' ? 'ใช้งานได้ทั้งครูและนักเรียนภายในโรงเรียน · v 1.2' : 'For all faculty and students · v 1.2'}
        </div>
      </div>
    </div>
  );
}

function RoleCard({ role, title, subtitle, icon, features, tint, grad, hover, onHover, onLeave, onClick, t }) {
  return (
    <button onClick={onClick} onMouseEnter={onHover} onMouseLeave={onLeave} style={{
      appearance:'none', border:0, cursor:'pointer',
      borderRadius: 26, padding: 26,
      background: hover ? grad : '#fff',
      color: hover ? '#fff' : 'var(--bp-ink)',
      textAlign:'left',
      display:'flex', flexDirection:'column', gap: 18,
      transition: 'background .25s ease, color .25s ease, transform .25s ease, box-shadow .25s ease',
      transform: hover ? 'translateY(-4px)' : 'translateY(0)',
      boxShadow: hover
        ? '0 24px 60px -20px rgba(80,50,180,0.45), 0 0 0 1px rgba(255,255,255,0.4) inset'
        : '0 1px 2px rgba(45,30,110,0.05), 0 8px 24px rgba(45,30,110,0.08), 0 0 0 1px var(--bp-line)',
      fontFamily:'inherit',
      position:'relative', overflow:'hidden',
    }}>
      {hover && (
        <>
          <div style={{ position:'absolute', right:-30, top:-30, width:140, height:140, borderRadius:'50%',
            background:'radial-gradient(circle, rgba(255,255,255,0.22), transparent 70%)' }}/>
          <div style={{ position:'absolute', left:-40, bottom:-50, width:160, height:160, borderRadius:'50%',
            background:'radial-gradient(circle, rgba(255,255,255,0.12), transparent 70%)' }}/>
        </>
      )}

      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', position:'relative' }}>
        <div style={{
          width: 54, height: 54, borderRadius: 16,
          background: hover ? 'rgba(255,255,255,0.20)' : tint + '14',
          color: hover ? '#fff' : tint,
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Icon name={icon} size={26} strokeWidth={1.7}/></div>
        <div style={{
          width: 36, height: 36, borderRadius:'50%',
          background: hover ? 'rgba(255,255,255,0.22)' : 'var(--bp-soft)',
          color: hover ? '#fff' : 'var(--bp-ink-3)',
          display:'flex', alignItems:'center', justifyContent:'center',
          transition: 'transform .25s ease',
          transform: hover ? 'translateX(4px)' : 'none',
        }}><Icon name="arrow_r" size={16}/></div>
      </div>

      <div style={{ position:'relative' }}>
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing:'-0.01em' }}>{title}</div>
        <div style={{ fontSize: 13.5, color: hover ? 'rgba(255,255,255,0.85)' : 'var(--bp-ink-3)', marginTop: 4 }}>{subtitle}</div>
      </div>

      <ul style={{
        listStyle:'none', padding: 0, margin: 0,
        display:'flex', flexDirection:'column', gap: 6,
        fontSize: 12.5, color: hover ? 'rgba(255,255,255,0.9)' : 'var(--bp-ink-2)',
        position:'relative',
      }}>
        {features.map(f => (
          <li key={f} style={{ display:'flex', alignItems:'center', gap: 8 }}>
            <Icon name="check" size={13} stroke={hover ? '#fff' : tint} strokeWidth={2.4}/>
            {f}
          </li>
        ))}
      </ul>

      <div style={{
        marginTop:'auto', paddingTop: 6,
        fontSize: 12.5, fontWeight: 600,
        color: hover ? '#fff' : tint,
        display:'flex', alignItems:'center', gap: 6,
        position:'relative',
      }}>
        {t.enter}
        <span style={{ transition:'transform .25s ease', transform: hover ? 'translateX(4px)' : 'none' }}>→</span>
      </div>
    </button>
  );
}

// ─── Role toggle pill ────────────────────────────────────────
function RoleToggle({ role, setRole, t, onLogout }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
      <div className="bp-role-toggle">
        <button onClick={() => setRole('student')} className={role === 'student' ? 'active' : ''}>
          <Icon name="user" size={14} stroke={role === 'student' ? '#fff' : 'currentColor'}/>
          {t.student}
        </button>
        <button onClick={() => setRole('teacher')} className={role === 'teacher' ? 'active' : ''}>
          <Icon name="layout" size={14} stroke={role === 'teacher' ? '#fff' : 'currentColor'}/>
          {t.teacher}
        </button>
      </div>
      <button onClick={onLogout} title={t.switchRole} style={{
        appearance:'none', cursor:'pointer',
        width: 38, height: 38, borderRadius: 999,
        border:'1px solid rgba(255,255,255,0.6)',
        background:'rgba(255,255,255,0.75)',
        backdropFilter:'blur(20px) saturate(180%)',
        color:'var(--bp-ink-2)',
        display:'flex', alignItems:'center', justifyContent:'center',
        boxShadow:'0 6px 24px rgba(45,30,110,0.10), 0 0 0 1px rgba(45,30,110,0.04)',
      }}>
        <Icon name="logout" size={16}/>
      </button>
    </div>
  );
}

// ─── Main app ────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "th",
  "theme": "light",
  "density": "regular",
  "showTweaks": true
}/*EDITMODE-END*/;

function App() {
  const [t_, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useStateA(() => {
    try { return localStorage.getItem('bp_lang') || t_.lang || 'th'; }
    catch { return t_.lang || 'th'; }
  });
  const [theme, setTheme] = useStateA(() => {
    try { return localStorage.getItem('bp_theme') || t_.theme || 'light'; }
    catch { return t_.theme || 'light'; }
  });
  const [auth, setAuth] = useStateA(null);
  const [authView, setAuthView] = useStateA('signin');
  const [role, setRole] = useStateA(null);
  const [reports, setReports] = useStateA(INITIAL_REPORTS);
  const [loadingSession, setLoadingSession] = useStateA(SB_CONFIGURED);
  const realtimeRef = useRefA(null);

  useEffectA(() => { if (t_.lang && t_.lang !== lang) setLang(t_.lang); }, [t_.lang]);
  useEffectA(() => { if (t_.theme && t_.theme !== theme) setTheme(t_.theme); }, [t_.theme]);
  useEffectA(() => { document.documentElement.dataset.theme = theme; }, [theme]);

  // Restore existing Supabase session on page load
  useEffectA(() => {
    if (!SB_CONFIGURED) return;
    sbGetSession()
      .then(async session => {
        if (session) {
          const r = await sbFetchReports().catch(() => null);
          if (r) setReports(r);
          setAuth({ id: session.user.email, userId: session.user.id, role: session.profile?.role || 'student', displayName: session.profile?.display_name, grade: session.profile?.grade, avatarUrl: session.profile?.avatar_url });
          setRole(session.profile?.role || 'student');
        }
      })
      .catch(() => {})
      .finally(() => setLoadingSession(false));
  }, []);

  // Realtime subscription while logged in
  useEffectA(() => {
    if (!auth?.userId) return;
    realtimeRef.current = sbSubscribeReports(
      r => setReports(prev => [r, ...prev.filter(x => x.id !== r.id)]),
      r => setReports(prev => prev.map(x => x.id === r.id ? r : x))
    );
    return () => sbUnsubscribe(realtimeRef.current);
  }, [auth?.userId]);

  function changeLang(l) {
    setLang(l); setTweak('lang', l);
    try { localStorage.setItem('bp_lang', l); } catch {}
  }
  function changeTheme(th) {
    setTheme(th); setTweak('theme', th);
    try { localStorage.setItem('bp_theme', th); } catch {}
  }

  const t = T[lang];

  if (loadingSession) {
    return (
      <div style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'100vh', background:'var(--bp-canvas)' }}>
        <Spinner/>
      </div>
    );
  }

  async function handleAuth(a) {
    setAuth(a);
    setRole(a.role || 'student');
    if (SB_CONFIGURED) {
      const r = await sbFetchReports().catch(() => null);
      if (r) setReports(r);
    }
  }

  // Auth phase
  if (!auth) {
    return authView === 'signup'
      ? <SignUpScreen
          onSignUp={(a) => { setAuth({ ...a, role: 'student' }); setRole('student'); setAuthView('signin'); }}
          onCancel={() => setAuthView('signin')}
          lang={lang} setLang={changeLang}/>
      : <AuthScreen
          onAuth={handleAuth}
          onSignUp={() => setAuthView('signup')}
          lang={lang} setLang={changeLang}/>;
  }

  // 3) App — as a real website
  const backChip = (
    <button
      onClick={() => { sbSignOut(); setAuth(null); setRole(null); }}
      className="bp-back-chip"
      title={lang === 'th' ? 'ออกจากระบบ' : 'Sign out'}
    >
      <Icon name="logout" size={13} stroke="currentColor"/>
      <span>{lang === 'th' ? 'ออกจากระบบ' : 'Sign out'}</span>
    </button>
  );

  const viewSwitcher = (
    <div className="bp-view-switch">
      <Icon name="eye" size={13} stroke="var(--bp-ink-3)"/>
      <span style={{ fontSize: 11.5, color:'var(--bp-ink-3)' }}>
        {lang === 'th' ? 'มุมมอง' : 'View as'}
      </span>
      <button
        className={role === 'student' ? '' : 'ghost'}
        onClick={() => setRole('student')}>
        <Icon name="user" size={11} stroke={role === 'student' ? '#fff' : 'currentColor'}/>
        {t.student}
      </button>
      <button
        className={role === 'teacher' ? '' : 'ghost'}
        onClick={() => setRole('teacher')}>
        <Icon name="layout" size={11} stroke={role === 'teacher' ? '#fff' : 'currentColor'}/>
        {t.teacher}
      </button>
    </div>
  );

  return (
    <>
      {role === 'student' && (
        <div className="bp-web-stage">
          <div className="bp-mobile-shell">
            <StudentApp
              lang={lang} setLang={changeLang}
              theme={theme} setTheme={changeTheme}
              reports={reports} setReports={setReports}
              initialUser={auth ? { name: auth.displayName || auth.id, grade: auth.grade || '', userId: auth.userId, photo: auth.avatarUrl } : undefined}/>
          </div>
          {backChip}
        </div>
      )}
      {role === 'teacher' && (
        <div style={{ height:'100vh', overflow:'hidden', position:'relative', background:'var(--bp-canvas)' }}>
          <TeacherApp
            lang={lang} setLang={changeLang}
            theme={theme} setTheme={changeTheme}
            reports={reports} setReports={setReports}
            initialUser={auth ? { name: auth.displayName || auth.id, userId: auth.userId, id: auth.id, photo: auth.avatarUrl } : undefined}
            onSwitchRole={() => setRole(null)}/>
          {backChip}
        </div>
      )}
      {/* Tweaks */}
      <TweaksPanel title="Tweaks">
        <TweakSection label={lang === 'th' ? 'มุมมอง' : 'View'}/>
        <TweakRadio label={lang === 'th' ? 'บทบาท' : 'Role'} value={role || 'student'}
          options={['student', 'teacher']}
          onChange={v => setRole(v)}/>
        <TweakRadio label={lang === 'th' ? 'ภาษา' : 'Language'} value={lang}
          options={['th', 'en']} onChange={changeLang}/>
        <TweakRadio label={lang === 'th' ? 'ธีม' : 'Theme'} value={theme}
          options={['light', 'dark']} onChange={changeTheme}/>
        <TweakSection label={lang === 'th' ? 'การทำงาน' : 'Actions'}/>
        <TweakButton label={lang === 'th' ? 'ออกจากระบบ' : 'Sign out'} onClick={() => { sbSignOut(); setAuth(null); setRole(null); }}/>
        <TweakButton label={lang === 'th' ? 'รีเซ็ตข้อมูล' : 'Reset data'} onClick={() => setReports(INITIAL_REPORTS)}/>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
