// src/features/student/ui/student-login.jsx
//
// The student sign-in screen (magic-link primary, legacy phone-cred
// fallback gated behind FEATURES.phoneLogin). Split off from
// student-dashboard.jsx so the parent stays under the 400 LOC budget.
//
// Depends on (via window): phoneDigits, phoneToEmail, phoneCredKey,
// readPhoneCred, stdBtnStyle, stdFieldStyle, useCaptcha,
// StudentOnboarding, AUTH, DASHBOARD_DATA, supa, FEATURES.
// Public: window.StudentLogin.

const { phoneDigits, phoneToEmail, phoneCredKey, readPhoneCred,
        stdBtnStyle, stdFieldStyle } = window;

const StudentLogin = ({ onLogin, onBack }) => {
  const [mode,        setMode]        = React.useState('email'); // 'email' | 'phone'
  const [email,       setEmail]       = React.useState('');
  const [phone,       setPhone]       = React.useState('');
  const [err,         setErr]         = React.useState('');
  const [busy,        setBusy]        = React.useState(false);
  const [magicSent,   setMagicSent]   = React.useState(false);
  const [showOnboard, setShowOnboard] = React.useState(false);
  const captcha = window.useCaptcha ? window.useCaptcha() : { token: null, widget: null, required: false };

  if (showOnboard) return <window.StudentOnboarding prefillPhone={phone} onComplete={onLogin} onBack={() => setShowOnboard(false)} />;

  const sendMagic = async (e) => {
    e.preventDefault();
    if (captcha.required) { setErr('Please complete the captcha.'); return; }
    setErr(''); setBusy(true);
    try {
      const { error } = await window.AUTH.sendMagicLink({ email: email.trim(), captchaToken: captcha.token });
      if (error) { setErr(error.message || "Couldn't send magic link."); return; }
      setMagicSent(true);
    } finally { setBusy(false); }
  };

  const phoneLookup = async (e) => {
    e.preventDefault();
    if (captcha.required) { setErr('Please complete the captcha.'); return; }
    setErr(''); setBusy(true);
    try {
      const loginEmail    = phoneToEmail(phone);
      const loginPassword = readPhoneCred(phone);
      if (!loginPassword) {
        setErr("This device doesn't have your account credentials cached. Use the email magic-link option above with the email you signed up with.");
        return;
      }
      const { error } = await window.supa.auth.signInWithPassword({
        email: loginEmail, password: loginPassword,
        options: captcha.token ? { captchaToken: captcha.token } : undefined,
      });
      if (error) {
        // Cached cred no longer works (password was rotated). Clear it.
        try { localStorage.removeItem(phoneCredKey(phone)); } catch (e) {}
        setErr("Sign-in failed. Use the email magic-link option above instead.");
        return;
      }
      await window.DASHBOARD_DATA.refresh();
      onLogin();
    } catch (e2) {
      setErr(e2.message || 'Sign-in failed.');
    } finally {
      setBusy(false);
    }
  };

  // An instructor who clicked the prominent navbar "Log In" lands here on the
  // student login. Both portals use the same role-agnostic magic link, but the
  // "Student login" label leaves tutors unsure they're in the right place — so
  // give them a one-click path to the branded Instructor login. getInitialPage
  // honors ?page=instructor-portal, and a full navigation is the same idiom the
  // become-instructor wizard uses for cross-portal hops.
  const goInstructorLogin = () => {
    try { window.location.assign(window.location.pathname + '?page=instructor-portal' + window.location.hash); }
    catch (_) { window.location.assign('/?page=instructor-portal'); }
  };

  return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:'oklch(98.5% 0.007 60)', fontFamily:"'Plus Jakarta Sans', sans-serif", padding:'24px', position:'relative' }}>
      {/* X close — Joe asked for a corner button instead of forcing users to
          scroll to the bottom for "← Back to site". */}
      <button onClick={onBack} aria-label="Close" title="Back to site"
        style={{ position:'absolute', top:18, right:18, width:38, height:38, borderRadius:'50%', background:'oklch(95% 0.005 60)', border:'1px solid oklch(90% 0.01 265)', cursor:'pointer', fontSize:18, lineHeight:1, color:'oklch(40% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", display:'flex', alignItems:'center', justifyContent:'center', zIndex:10 }}>
        ×
      </button>
      <div style={{ width:'100%', maxWidth:400 }}>
        <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:22, fontWeight:700, letterSpacing:'0.12em', color:'oklch(22% 0.06 265)', marginBottom:48, textAlign:'center' }}>COACHING</div>
        <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:30, fontWeight:600, color:'oklch(18% 0.03 265)', marginBottom:6 }}>Student login</div>
        {!magicSent && (
          <div style={{ fontSize:13.5, color:'oklch(48% 0.04 265)', marginBottom:18, lineHeight:1.5 }}>
            Are you an instructor?{' '}
            <button type="button" onClick={goInstructorLogin}
              style={{ background:'none', border:'none', padding:0, color:'oklch(48% 0.18 265)', cursor:'pointer', fontWeight:700, fontSize:13.5, textDecoration:'underline', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
              Log in here →
            </button>
          </div>
        )}

        {magicSent ? (
          <>
            <div style={{ fontSize:16, color:'oklch(38% 0.04 265)', marginBottom:24, lineHeight:1.7 }}>📧 Check your inbox at <strong>{email}</strong> — click the link in the email to sign in. The tab will reload automatically.</div>
            <button onClick={() => { setMagicSent(false); setEmail(''); }} style={stdBtnStyle(false)}>Use a different email</button>
          </>
        ) : mode === 'email' ? (
          <>
            <div style={{ fontSize:16, color:'oklch(58% 0.03 265)', marginBottom:32, lineHeight:1.7 }}>Enter your email — we'll send you a magic link to sign in.</div>
            <form onSubmit={sendMagic}>
              <input type="email" value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} placeholder="you@email.com" style={{...stdFieldStyle, marginBottom:err?8:18}} autoFocus />
              {captcha.widget}
              {err && <div style={{ fontSize:14, color:'oklch(38% 0.09 25)', marginBottom:18, lineHeight:1.55, background:'oklch(97% 0.06 25)', padding:'10px 14px', borderRadius:10 }}>{err}</div>}
              <button type="submit" disabled={busy || !email.includes('@') || captcha.required} style={stdBtnStyle(true)}>{busy ? 'Sending…' : '📧 Send magic link'}</button>
            </form>
          </>
        ) : (
          <>
            <div style={{ fontSize:16, color:'oklch(58% 0.03 265)', marginBottom:32, lineHeight:1.7 }}>Enter the phone number you signed up with (legacy login).</div>
            <form onSubmit={phoneLookup}>
              <input type="tel" value={phone} onChange={e => { setPhone(e.target.value); setErr(''); }} placeholder="(212) 555-0000" style={{...stdFieldStyle, marginBottom:err?8:18}} autoFocus />
              {captcha.widget}
              {err && <div style={{ fontSize:14, color:'oklch(38% 0.09 25)', marginBottom:18, lineHeight:1.55, background:'oklch(97% 0.06 25)', padding:'10px 14px', borderRadius:10 }}>{err}</div>}
              <button type="submit" disabled={busy || phoneDigits(phone).length < 7 || captcha.required} style={stdBtnStyle(true)}>{busy ? 'Signing in…' : 'Find my account →'}</button>
            </form>
          </>
        )}

        {!magicSent && (
          <div style={{ display:'flex', flexDirection:'column', gap:12, marginTop:16 }}>
            {/* Phone-login toggle is gated on the FEATURES.phoneLogin flag. v1.5
                is invite-only via magic link, so we hide this. The phone code
                path stays in place so we can flip the flag back on later. */}
            {window.FEATURES?.phoneLogin && (
              <button onClick={() => { setMode(mode === 'email' ? 'phone' : 'email'); setErr(''); }} style={{ background:'none', border:'none', fontSize:14, color:'oklch(50% 0.04 265)', cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", padding:'4px 0', textAlign:'center', textDecoration:'underline' }}>
                {mode === 'email' ? 'Use phone number instead →' : '← Use email magic link instead'}
              </button>
            )}
            {/* Self-serve account creation is also tied to the public-instructor
                flow — when public is off, students arrive via admin invite. */}
            {window.FEATURES?.publicInstructors && (
              <button onClick={() => setShowOnboard(true)} style={stdBtnStyle(false)}>New student? Create account</button>
            )}
            <button onClick={onBack} style={{ background:'none', border:'none', fontSize:15, color:'oklch(62% 0.03 265)', cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", padding:'8px 0', textAlign:'center' }}>← Back to site</button>
          </div>
        )}
      </div>
    </div>
  );
};

window.StudentLogin = StudentLogin;
