// Login + Forgot Password flow

function Login(){
  const store = useStore();
  const toast = useToast();
  const [stage, setStage] = React.useState('signin'); // signin | forgot | reset
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [resetCode, setResetCode] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');



  async function submit(e){
    e.preventDefault();
    setBusy(true); setErr('');
    const r = await store.login(email, password);
    setBusy(false);
    if(!r.ok){ setErr(r.error); return; }
    toast(`Welcome, ${r.user.name.split(' ')[0]}`);
  }

  async function doForgot(e){
    e.preventDefault();
    if(!email) return setErr('Enter your email address');
    setBusy(true); setErr('');
    try {
      const res = await store.requestPasswordReset(email);
      setBusy(false);
      if(res.ok){ setStage('reset'); toast('Reset code sent to your email'); }
      else setErr('Could not request password reset');
    } catch(err){ setBusy(false); setErr(err.message || 'Error requesting reset'); }
  }

  async function doReset(e){
    e.preventDefault();
    if(!resetCode || !newPassword) return setErr('Enter code and new password');
    setBusy(true); setErr('');
    try {
      const res = await store.resetPassword(email, resetCode, newPassword);
      setBusy(false);
      if(res.ok){
        setStage('signin');
        setPassword('');
        toast('Password reset successfully! Please sign in.');
      } else setErr('Could not reset password');
    } catch(err){ setBusy(false); setErr(err.message || 'Error resetting password'); }
  }


  return (
    <div className="auth">
      <div className="auth-side">
        <div className="brand">
          <img src="/favicon.ico" alt="Merida logo" style={{ width: 32, height: 32, borderRadius: 8 }} />
          <div>
            <div className="brand-name">Merida</div>
            <div className="brand-sub">Skill Learning Academy</div>
          </div>
        </div>
        <div>
          <p className="auth-headline">
            One calm place to run <em>classes</em>, cohorts and team meetings.
          </p>
        </div>
        <div className="auth-footer">
          © Merida 2026
        </div>
        <div className="deco" />
      </div>

      <div className="auth-main">
        <div className="auth-card">

          {stage === 'signin' && (
            <React.Fragment>
              <h2>Sign in</h2>
              <p className="sub">Use your registered email and password.</p>
              <form onSubmit={submit}>
                <label className="field">
                  <span className="field-label">Email address</span>
                  <input className="input" type="email" placeholder="you@merida.in"
                    value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} autoFocus />
                </label>
                <label className="field">
                  <span className="field-label">Password</span>
                  <div style={{ position:'relative' }}>
                    <input className="input" type={showPw?'text':'password'} placeholder="••••••••"
                      value={password} onChange={e => { setPassword(e.target.value); setErr(''); }} />
                    <button type="button" onClick={() => setShowPw(v=>!v)}
                      style={{ position:'absolute', right:8, top:'50%', transform:'translateY(-50%)', border:0, background:'transparent', cursor:'pointer', fontSize:11, fontWeight:600, color:'var(--ink-3)', padding:'4px 8px' }}>
                      {showPw ? 'Hide' : 'Show'}
                    </button>
                  </div>
                  <div style={{ textAlign:'right', marginTop:6 }}>
                    <a href="#" style={{ fontSize:12, fontWeight:500, color:'var(--accent)' }} onClick={(e)=>{ e.preventDefault(); setStage('forgot'); setErr(''); }}>Forgot password?</a>
                  </div>
                </label>
                {err && <ErrBox msg={err} />}
                <button className="btn accent" style={{ width:'100%', justifyContent:'center', padding:'11px' }} type="submit" disabled={busy}>
                  {busy ? 'Signing in…' : <React.Fragment>Continue <Icon name="arrow" /></React.Fragment>}
                </button>
              </form>

            </React.Fragment>
          )}

          {stage === 'forgot' && (
            <React.Fragment>
              <button className="btn ghost" style={{ marginBottom:16, padding:'4px 8px', fontSize:13 }} onClick={() => { setStage('signin'); setErr(''); }}>
                <Icon name="arrow" style={{ transform:'rotate(180deg)' }}/> Back
              </button>
              <h2>Reset Password</h2>
              <p className="sub">Enter your email and we'll send you a 6-digit code.</p>
              <form onSubmit={doForgot}>
                <label className="field">
                  <span className="field-label">Email address</span>
                  <input className="input" type="email" placeholder="you@merida.in"
                    value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} autoFocus />
                </label>
                {err && <ErrBox msg={err} />}
                <button className="btn accent" style={{ width:'100%', justifyContent:'center', padding:'11px' }} type="submit" disabled={busy}>
                  {busy ? 'Sending…' : 'Send Reset Code'}
                </button>
              </form>
            </React.Fragment>
          )}

          {stage === 'reset' && (
            <React.Fragment>
              <button className="btn ghost" style={{ marginBottom:16, padding:'4px 8px', fontSize:13 }} onClick={() => { setStage('forgot'); setErr(''); }}>
                <Icon name="arrow" style={{ transform:'rotate(180deg)' }}/> Back
              </button>
              <h2>Enter Code</h2>
              <p className="sub">We sent a 6-character code to <strong>{email}</strong>.</p>
              <form onSubmit={doReset}>
                <label className="field">
                  <span className="field-label">Reset Code</span>
                  <input className="input" type="text" placeholder="e.g. A1B2C3" style={{ textTransform:'uppercase', letterSpacing:1.5 }}
                    value={resetCode} onChange={e => { setResetCode(e.target.value); setErr(''); }} autoFocus />
                </label>
                <label className="field">
                  <span className="field-label">New Password</span>
                  <input className="input" type="password" placeholder="Min 6 characters"
                    value={newPassword} onChange={e => { setNewPassword(e.target.value); setErr(''); }} />
                </label>
                {err && <ErrBox msg={err} />}
                <button className="btn accent" style={{ width:'100%', justifyContent:'center', padding:'11px' }} type="submit" disabled={busy}>
                  {busy ? 'Saving…' : 'Save New Password'}
                </button>
              </form>
            </React.Fragment>
          )}

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

function ErrBox({ msg }){
  return <div style={{ background:'var(--warn-soft)', color:'var(--warn)', padding:'8px 12px', borderRadius:8, fontSize:12.5, fontWeight:600, marginBottom:14 }}>{msg}</div>;
}

Object.assign(window, { Login });
