// Auth (signup, login, forgot) — backed by Supabase Auth (window.RR.auth),
// which transparently falls back to a mock session when Supabase isn't configured.
function AuthScreen({ go, mode = 'signup', onAuth }) {
  const [showPw, setShowPw] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('');

  const isSignup = mode === 'signup';
  const emailOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email);

  const submit = async (e) => {
    e?.preventDefault();
    if (isSignup && !name.trim()) { setError("What's your name?"); return; }
    if (!emailOk) { setError("That email doesn't look right."); return; }
    if (pw.length < 6) { setError("Password needs at least 6 characters."); return; }
    setError(''); setNotice('');
    setSubmitting(true);
    try {
      const { user, session, error: err } = isSignup
        ? await window.RR.auth.signUp(email, pw, name.trim())
        : await window.RR.auth.signIn(email, pw);
      setSubmitting(false);
      if (err) { setError(err.message || 'Something went wrong.'); return; }
      if (user) onAuth?.(user);
      // Supabase signups with email confirmation return a user but no session.
      if (isSignup && window.RR.auth.enabled && !session) {
        setNotice("Check your email to confirm your account, then log in.");
        return;
      }
      go(isSignup ? 'welcome' : 'dashboard');
    } catch (ex) {
      setSubmitting(false);
      setError(ex.message || 'Network error.');
    }
  };

  const googleSignIn = async () => {
    const { error: err, mock } = await window.RR.auth.signInWithGoogle();
    if (err) { setError(err.message); return; }
    // Real OAuth redirects away; mock just advances the flow.
    if (mock) go(isSignup ? 'welcome' : 'dashboard');
  };

  return (
    <div style={{ minHeight: '100%', display:'flex', alignItems:'center', justifyContent:'center', padding: 24, background: 'radial-gradient(ellipse at 30% 20%, rgba(255,92,57,0.06), transparent 50%), radial-gradient(ellipse at 80% 80%, rgba(30,58,138,0.04), transparent 50%), var(--bg-canvas)' }}>
      <div className="card card-lg fade-up" style={{ maxWidth: 440, width:'100%', padding: 40, boxShadow:'var(--shadow-lg)' }}>
        <div style={{ display:'flex', justifyContent:'center', marginBottom: 24 }}><Wordmark size="md"/></div>
        <h2 className="t-h2" style={{ textAlign:'center', margin: 0 }}>
          {isSignup ? "Create your account" : "Welcome back"}
        </h2>
        <p className="t-body secondary" style={{ textAlign:'center', marginTop: 8, marginBottom: 28 }}>
          {isSignup ? "Free to start. No credit card." : "Glad you're back."}
        </p>

        <Btn variant="secondary" size="lg" className="full" style={{ width:'100%' }} onClick={googleSignIn}>
          <Icon.google size={18}/> Continue with Google
        </Btn>

        {notice && <div className="t-body-sm" style={{ textAlign:'center', marginTop: 16, color:'var(--success)' }}>{notice}</div>}

        <div style={{ display:'flex', alignItems:'center', gap: 12, margin: '20px 0', color:'var(--text-muted)', fontSize: 13 }}>
          <div style={{ flex: 1, height: 1, background:'var(--border-default)' }}/>
          or
          <div style={{ flex: 1, height: 1, background:'var(--border-default)' }}/>
        </div>

        <form onSubmit={submit} className="stack">
          {isSignup && (
            <Input
              label="Full name"
              type="text"
              placeholder="Jane Smith"
              value={name}
              onChange={e=>setName(e.target.value)}
              autoFocus
            />
          )}
          <Input
            label="Email"
            type="email"
            placeholder="you@email.com"
            value={email}
            onChange={e=>setEmail(e.target.value)}
            error={error}
            autoFocus={!isSignup}
          />
          <div style={{ position:'relative' }}>
            <Input
              label="Password"
              type={showPw ? "text" : "password"}
              placeholder={isSignup ? "At least 6 characters" : "Your password"}
              value={pw}
              onChange={e=>setPw(e.target.value)}
            />
            <button type="button" onClick={()=>setShowPw(!showPw)} style={{ position:'absolute', right: 12, top: 36, background:'transparent', border: 0, color:'var(--text-muted)', cursor:'pointer', padding: 6 }}>
              <Icon.eye size={16}/>
            </button>
          </div>

          {!isSignup && (
            <div style={{ textAlign:'right', marginTop: -8 }}>
              <a href="#" className="t-body-sm" style={{ color:'var(--accent-secondary)', textDecoration:'none' }} onClick={(e)=>{e.preventDefault(); go('forgot');}}>Forgot password?</a>
            </div>
          )}

          <Btn variant="primary" size="lg" type="submit" style={{ width:'100%', marginTop: 8 }} loading={submitting}>
            {isSignup ? "Create account" : "Log in"}
          </Btn>
        </form>

        <div className="t-body-sm muted" style={{ textAlign:'center', marginTop: 20, lineHeight: 1.5 }}>
          {isSignup ? (
            <>
              By continuing, you agree to our <a href="/terms.html" target="_blank" rel="noopener" style={{ color:'var(--accent-secondary)' }}>Terms</a> and <a href="/privacy.html" target="_blank" rel="noopener" style={{ color:'var(--accent-secondary)' }}>Privacy Policy</a>.
            </>
          ) : null}
        </div>

        <div className="t-body-sm" style={{ textAlign:'center', marginTop: 16, color: 'var(--text-secondary)' }}>
          {isSignup ? (
            <>Already have an account? <a href="#" onClick={(e)=>{e.preventDefault(); go('login');}} style={{ color:'var(--accent-primary)' }}>Log in</a></>
          ) : (
            <>New here? <a href="#" onClick={(e)=>{e.preventDefault(); go('signup');}} style={{ color:'var(--accent-primary)' }}>Create an account</a></>
          )}
        </div>
      </div>
    </div>
  );
}

function ForgotScreen({ go }) {
  const [sent, setSent] = useState(false);
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const sendReset = async (e) => {
    e.preventDefault();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setError("That email doesn't look right."); return; }
    setError(''); setSubmitting(true);
    const { error: err } = await window.RR.auth.resetPassword(email);
    setSubmitting(false);
    if (err) { setError(err.message || 'Could not send the reset link.'); return; }
    setSent(true);
  };
  return (
    <div style={{ minHeight: '100%', display:'flex', alignItems:'center', justifyContent:'center', padding: 24, background:'var(--bg-canvas)' }}>
      <div className="card card-lg fade-up" style={{ maxWidth: 440, width:'100%', padding: 40, boxShadow:'var(--shadow-lg)' }}>
        <div style={{ display:'flex', justifyContent:'center', marginBottom: 24 }}><Wordmark size="md"/></div>
        {!sent ? (
          <>
            <h2 className="t-h2" style={{ textAlign:'center', margin: 0 }}>Forgot your password?</h2>
            <p className="t-body secondary" style={{ textAlign:'center', marginTop: 8, marginBottom: 28 }}>Pop your email in and we'll send a reset link.</p>
            <form onSubmit={sendReset} className="stack">
              <Input label="Email" type="email" placeholder="you@email.com" value={email} onChange={e=>setEmail(e.target.value)} error={error} autoFocus/>
              <Btn variant="primary" size="lg" type="submit" style={{ width:'100%' }} loading={submitting}>Send reset link</Btn>
              <div className="t-body-sm" style={{ textAlign:'center' }}>
                <a href="#" onClick={(e)=>{e.preventDefault(); go('login');}} style={{ color: 'var(--accent-primary)' }}>Back to log in</a>
              </div>
            </form>
          </>
        ) : (
          <div style={{ textAlign:'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background:'rgba(22,163,74,0.1)', color:'var(--success)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom: 16 }}>
              <Icon.mail size={28}/>
            </div>
            <h2 className="t-h2" style={{ margin: 0 }}>Check your inbox.</h2>
            <p className="t-body secondary" style={{ marginTop: 8, marginBottom: 28 }}>If that email exists, the reset link is on its way.</p>
            <Btn variant="secondary" onClick={()=>go('login')}>Back to log in</Btn>
          </div>
        )}
      </div>
    </div>
  );
}

// Welcome screen
function WelcomeScreen({ go, user }) {
  const name = (user?.user_metadata?.full_name?.split(' ')[0]) || user?.email?.split('@')[0] || 'there';
  return (
    <div style={{ minHeight: '100%', display: 'flex', alignItems:'center', justifyContent:'center', position:'relative', overflow:'hidden', padding: 24 }}>
      <div className="particles">
        {Array.from({length: 18}).map((_,i)=>(
          <span key={i} style={{
            left: `${(i * 53) % 100}%`,
            top: `${(i * 37) % 100}%`,
            animationDelay: `${i * 0.3}s`,
            opacity: 0.06 + (i % 4) * 0.04,
            width: 4 + (i % 3) * 2,
            height: 4 + (i % 3) * 2,
          }}/>
        ))}
      </div>
      <div style={{ position:'relative', maxWidth: 600, textAlign:'center' }} className="fade-up">
        <img src="assets/brand/icon.png" alt="Resumerush" style={{ width: 64, height: 64, borderRadius: 18, display: 'block', margin: '0 auto 32px', animation:'pulse 3s var(--e-inout) infinite' }}/>
        <h1 className="t-display" style={{ marginBottom: 20, fontSize: 56 }}>
          Hey <span style={{ animation: 'fadeUp 0.6s var(--e-out) 0.35s both', display:'inline-block' }}>{name}</span> — let's build something good.
        </h1>
        <p className="t-body-lg secondary" style={{ marginBottom: 40, marginInline: 'auto', maxWidth: 480 }}>
          I'll ask you about 30 questions. Most are one tap. The whole thing takes about 6 minutes. You can pause anytime.
        </p>
        <div style={{ display: 'flex', gap: 12, justifyContent:'center', flexWrap:'wrap' }}>
          <Btn variant="primary" size="lg" onClick={()=>go('survey')} iconRight={<Icon.arrowRight size={18}/>}>Start the survey</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, ForgotScreen, WelcomeScreen });
