/* ============================================================
   AuthScreen — sign in / sign up with email+password + Google OAuth.
   Backed by Supabase Auth (window.sb). Matches the prototype's
   visual language (Btn / Card primitives, OKLCH vars).

   2026-06-05 7:25PM — NEW FILE. Supabase auth wall for the app.
   What: a self-contained auth screen registered as DETAIL_SCREEN 'auth'.
         Email/password (signInWithPassword / signUp) is the primary path;
         "Continue with Google" via signInWithOAuth (provider may not be
         configured in Supabase yet — errors surface kindly).
   Why: doc 04 §2 — anonymous-try / auth-to-save; Profile + save-progress
        actions route here when there is no session.
   Status: ⚠️ PENDING USER TESTING
   ============================================================ */
(function () {
  const { useState } = React;

  // Friendly mapping for the most common Supabase auth errors (fail loudly, kindly).
  function friendly(msg) {
    if (!msg) return 'Something went wrong. Please try again.';
    const m = String(msg).toLowerCase();
    if (m.includes('invalid login')) return 'That email or password doesn’t match. Try again.';
    if (m.includes('already registered') || m.includes('already been registered')) return 'That email already has an account — try signing in instead.';
    if (m.includes('password should be') || m.includes('at least')) return 'Password must be at least 6 characters.';
    if (m.includes('email') && m.includes('valid')) return 'Please enter a valid email address.';
    if (m.includes('confirm') || m.includes('confirmation')) return 'Check your inbox to confirm your email, then sign in.';
    if (m.includes('provider is not enabled') || m.includes('not enabled') || m.includes('unsupported provider')) return 'Google sign-in isn’t available yet — use email and password for now.';
    return msg;
  }

  // Local field (Field lives inside profile.jsx's IIFE and isn't exported on window).
  function AuthField({ label, value, onChange, type = 'text', placeholder }) {
    return (
      <div style={{ marginBottom: 16 }}>
        <label style={{ display: 'block', fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 700, fontSize: 12,
          color: 'var(--muted)', padding: '0 4px 6px' }}>{label}</label>
        <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          autoCapitalize="none" autoCorrect="off" spellCheck={false}
          style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--line)', borderRadius: 14,
            padding: '13px 15px', background: 'var(--surface)', fontFamily: '"Hanken Grotesk",system-ui',
            fontSize: 16, fontWeight: 600, color: 'var(--ink)', outline: 'none' }} />
      </div>
    );
  }

  function GoogleMark() {
    return (
      <svg width="18" height="18" viewBox="0 0 48 48" style={{ flexShrink: 0 }}>
        <path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.6l6.8-6.8C35.6 2.6 30.2 0 24 0 14.6 0 6.4 5.4 2.5 13.2l7.9 6.1C12.2 13.6 17.6 9.5 24 9.5z"/>
        <path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.5 3-2.2 5.5-4.7 7.2l7.3 5.7c4.3-3.9 6.7-9.7 6.7-17.4z"/>
        <path fill="#FBBC05" d="M10.4 28.7c-.5-1.5-.8-3-.8-4.7s.3-3.2.8-4.7l-7.9-6.1C.9 16.3 0 20 0 24s.9 7.7 2.5 10.8l7.9-6.1z"/>
        <path fill="#34A853" d="M24 48c6.2 0 11.4-2 15.2-5.6l-7.3-5.7c-2 1.4-4.7 2.3-7.9 2.3-6.4 0-11.8-4.1-13.6-9.8l-7.9 6.1C6.4 42.6 14.6 48 24 48z"/>
      </svg>
    );
  }

  function AuthScreen({ nav }) {
    const [mode, setMode] = useState('signin');   // 'signin' | 'signup'
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState('');
    const [note, setNote] = useState('');         // success / confirm-email note

    const submit = async () => {
      setErr(''); setNote('');
      if (!email.trim() || !password) { setErr('Enter your email and password.'); return; }
      if (!window.sb) { setErr('Sign-in isn’t ready yet. Reload and try again.'); return; }
      setBusy(true);
      try {
        if (mode === 'signup') {
          const { data, error } = await window.sb.auth.signUp({ email: email.trim(), password });
          if (error) { setErr(friendly(error.message)); return; }
          // If email confirmation is ON, there's no session yet.
          if (data && data.session) {
            nav.home();
          } else {
            setNote('Account created. Check your inbox to confirm your email, then sign in.');
            setMode('signin');
          }
        } else {
          const { error } = await window.sb.auth.signInWithPassword({ email: email.trim(), password });
          if (error) { setErr(friendly(error.message)); return; }
          nav.home();
        }
      } catch (e) {
        setErr(friendly(e && e.message));
      } finally {
        setBusy(false);
      }
    };

    const google = async () => {
      setErr(''); setNote('');
      if (!window.sb) { setErr('Sign-in isn’t ready yet. Reload and try again.'); return; }
      setBusy(true);
      try {
        const { error } = await window.sb.auth.signInWithOAuth({
          provider: 'google',
          options: { redirectTo: window.location.origin + '/' },
        });
        // On success the browser redirects away; if we're still here, surface the error.
        if (error) setErr(friendly(error.message));
      } catch (e) {
        setErr(friendly(e && e.message));
      } finally {
        setBusy(false);
      }
    };

    const onKey = (e) => { if (e.key === 'Enter') submit(); };

    return (
      <div style={{ minHeight: '100%', background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
        {/* header */}
        <div style={{ padding: '50px 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ fontFamily: '"Bricolage Grotesque",system-ui', fontWeight: 800, fontSize: 22, color: 'var(--ink)', letterSpacing: '-0.02em' }}>
            {mode === 'signup' ? 'Create account' : 'Sign in'}
          </div>
          <IconBtn kind="close" onClick={nav.back} />
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 20px 40px' }}>
          {/* mascot + intro */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding: '6px 0 22px' }}>
            <Mascot size={76} />
            <div style={{ fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 600, fontSize: 14, color: 'var(--muted)', textAlign: 'center', maxWidth: 280, lineHeight: 1.45 }}>
              {mode === 'signup'
                ? 'Save your streak, sync across devices, and keep your progress forever.'
                : 'Welcome back — your streak is waiting.'}
            </div>
          </div>

          {/* Google */}
          <Btn variant="outline" full onClick={busy ? undefined : google} disabled={busy}
            style={{ marginBottom: 14, fontWeight: 700 }}>
            <GoogleMark /> Continue with Google
          </Btn>

          {/* divider */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '4px 0 16px' }}>
            <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            <span style={{ fontFamily: '"JetBrains Mono",monospace', fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em', color: 'var(--muted)', textTransform: 'uppercase' }}>or</span>
            <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
          </div>

          {/* email + password */}
          <AuthField label="Email" value={email} onChange={setEmail} type="email" placeholder="you@example.com" />
          <div onKeyDown={onKey}>
            <AuthField label="Password" value={password} onChange={setPassword} type="password"
              placeholder={mode === 'signup' ? 'At least 6 characters' : '••••••••'} />
          </div>

          {note && (
            <div style={{ background: 'var(--primary-wash)', borderRadius: 14, padding: '12px 14px', marginBottom: 14,
              fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 600, fontSize: 13, color: 'var(--primary-deep)', lineHeight: 1.4 }}>
              {note}
            </div>
          )}
          {err && (
            <div style={{ background: 'oklch(0.95 0.04 25)', borderRadius: 14, padding: '12px 14px', marginBottom: 14,
              fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 600, fontSize: 13, color: 'oklch(0.50 0.17 25)', lineHeight: 1.4 }}>
              {err}
            </div>
          )}

          <Btn full onClick={busy ? undefined : submit} disabled={busy} style={{ marginTop: 4 }}>
            {busy ? 'Please wait…' : (mode === 'signup' ? 'Create account' : 'Sign in')}
          </Btn>

          {/* mode switch */}
          <div style={{ textAlign: 'center', paddingTop: 18, fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 600, fontSize: 13.5, color: 'var(--muted)' }}>
            {mode === 'signup' ? 'Already have an account?' : 'New here?'}{' '}
            <button onClick={() => { setErr(''); setNote(''); setMode(mode === 'signup' ? 'signin' : 'signup'); }}
              style={{ appearance: 'none', border: 'none', background: 'transparent', cursor: 'pointer',
                fontFamily: '"Hanken Grotesk",system-ui', fontWeight: 800, fontSize: 13.5, color: 'var(--primary-deep)' }}>
              {mode === 'signup' ? 'Sign in' : 'Create one'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.AuthScreen = AuthScreen;
})();
