// Auth screen — Sign In / Sign Up with email+password and Google

function AuthScreen({ inviteBanner }) {
  const [mode, setMode]         = React.useState(inviteBanner ? 'signup' : 'signin'); // 'signin' | 'signup'
  const [name, setName]         = React.useState('');
  const [gamertag, setGamertag] = React.useState('');
  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm]   = React.useState('');
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState(null);

  const reset = () => { setError(null); setLoading(false); };

  const signInGoogle = async () => {
    setLoading(true); setError(null);
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      await window.fbAuth.signInWithPopup(provider);
    } catch (e) {
      if (e.code !== 'auth/popup-closed-by-user') setError(friendlyError(e.code));
      reset();
    }
  };

  const signIn = async (e) => {
    e.preventDefault();
    setLoading(true); setError(null);
    try {
      await window.fbAuth.signInWithEmailAndPassword(email.trim(), password);
    } catch (e) {
      setError(friendlyError(e.code));
      reset();
    }
  };

  const signUp = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setError('Bitte gib deinen Namen ein.'); return; }
    if (password.length < 6) { setError('Passwort muss mindestens 6 Zeichen haben.'); return; }
    if (password !== confirm) { setError('Passwörter stimmen nicht überein.'); return; }
    setLoading(true); setError(null);
    try {
      const cred = await window.fbAuth.createUserWithEmailAndPassword(email.trim(), password);
      await cred.user.updateProfile({ displayName: name.trim() });
      if (gamertag.trim() && window.fbDb) {
        try {
          await window.fbDb.collection('users').doc(cred.user.uid)
            .set({ gamertag: gamertag.trim() }, { merge: true });
        } catch (_) { /* best-effort — profile can be set later */ }
      }
    } catch (e) {
      setError(friendlyError(e.code));
      reset();
    }
  };

  const isSignIn = mode === 'signin';
  const label = { color: 'oklch(0.68 0.022 285)', fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 6, letterSpacing: 0.4, textTransform: 'uppercase' };
  const input = {
    width: '100%', padding: '11px 14px',
    background: 'oklch(0.27 0.03 285)',
    border: '1px solid oklch(0.32 0.025 285)',
    borderRadius: 10, color: 'oklch(0.96 0.012 285)',
    fontFamily: "'Space Grotesk', system-ui", fontSize: 14,
    outline: 'none', boxSizing: 'border-box',
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, overflowY: 'auto',
      overscrollBehavior: 'contain', WebkitOverflowScrolling: 'touch',
      background: 'radial-gradient(ellipse at top, oklch(0.18 0.04 285) 0%, oklch(0.12 0.025 285) 70%)',
      fontFamily: "'Space Grotesk', system-ui, sans-serif",
    }}>
    <div style={{
      minHeight: '100%', boxSizing: 'border-box',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '24px 20px',
      paddingTop: 'max(24px, env(safe-area-inset-top))',
      paddingBottom: 'max(24px, env(safe-area-inset-bottom))',
    }}>
      <div style={{
        width: '100%', maxWidth: 360,
        background: 'oklch(0.215 0.028 285)',
        border: '1px solid oklch(0.32 0.025 285)',
        borderRadius: 28, padding: 28,
        boxShadow: '0 40px 80px rgba(0,0,0,0.45)',
      }}>
        {/* Logo */}
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16, margin: '0 auto 14px',
            background: 'color-mix(in oklab, #aaff66 14%, transparent)',
            border: '1px solid color-mix(in oklab, #aaff66 30%, transparent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 26,
          }}>🎮</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'oklch(0.96 0.012 285)', letterSpacing: -0.5 }}>
            Zocker-Abstimmung
          </div>
          <div style={{ fontSize: 13, color: 'oklch(0.68 0.022 285)', marginTop: 4 }}>
            Bock zu zocken? Plan Sessions mit deiner Crew.
          </div>
        </div>

        {/* Invite banner — arrived via a shared group link */}
        {inviteBanner && (
          <div style={{
            padding: '12px 14px', marginBottom: 18, borderRadius: 12,
            background: 'color-mix(in oklab, #aaff66 12%, transparent)',
            border: '1px solid color-mix(in oklab, #aaff66 30%, transparent)',
            color: '#aaff66', fontSize: 13, lineHeight: 1.45,
            display: 'flex', alignItems: 'flex-start', gap: 8,
          }}>
            <span style={{ fontSize: 16, lineHeight: 1 }}>🎮</span>
            <span>Du wurdest zu <strong>„{inviteBanner.groupName}"</strong> eingeladen. Melde dich an, um beizutreten.</span>
          </div>
        )}

        {/* Tab toggle */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr',
          background: 'oklch(0.27 0.03 285)', borderRadius: 12, padding: 3,
          marginBottom: 22,
        }}>
          {[['signin', 'Anmelden'], ['signup', 'Registrieren']].map(([m, label]) => (
            <button key={m} onClick={() => { setMode(m); setError(null); }} style={{
              appearance: 'none', cursor: 'pointer', border: 0,
              padding: '8px 0', borderRadius: 9,
              background: mode === m ? '#aaff66' : 'transparent',
              color: mode === m ? '#0a1428' : 'oklch(0.68 0.022 285)',
              fontFamily: "'Space Grotesk', system-ui", fontSize: 13, fontWeight: 700,
              transition: 'all 180ms ease',
            }}>{label}</button>
          ))}
        </div>

        {/* Google button */}
        <button onClick={signInGoogle} disabled={loading} style={{
          width: '100%', padding: '12px 16px', marginBottom: 16,
          background: 'oklch(0.27 0.03 285)',
          border: '1px solid oklch(0.32 0.025 285)', borderRadius: 12,
          cursor: loading ? 'not-allowed' : 'pointer',
          fontFamily: "'Space Grotesk', system-ui", fontSize: 14, fontWeight: 600,
          color: 'oklch(0.96 0.012 285)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
          </svg>
          Mit Google {isSignIn ? 'anmelden' : 'registrieren'}
        </button>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16,
          color: 'oklch(0.45 0.02 285)', fontSize: 11,
        }}>
          <div style={{ flex: 1, height: 1, background: 'oklch(0.32 0.025 285)' }} />
          oder
          <div style={{ flex: 1, height: 1, background: 'oklch(0.32 0.025 285)' }} />
        </div>

        {/* Email/password form */}
        <form onSubmit={isSignIn ? signIn : signUp} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {!isSignIn && (
            <div>
              <label style={label}>Vorname</label>
              <input
                type="text" value={name} onChange={e => setName(e.target.value)}
                placeholder="Dein Vorname" required
                style={input}
              />
            </div>
          )}
          {!isSignIn && (
            <div>
              <label style={label}>Gamertag</label>
              <input
                type="text" value={gamertag} onChange={e => setGamertag(e.target.value)}
                placeholder="z.B. xX_Sniper_Xx"
                style={input}
              />
            </div>
          )}
          <div>
            <label style={label}>E-Mail</label>
            <input
              type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="deine@email.de" required
              style={input}
            />
          </div>
          <div>
            <label style={label}>Passwort</label>
            <input
              type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder={isSignIn ? '••••••••' : 'Min. 6 Zeichen'} required
              style={input}
            />
          </div>
          {!isSignIn && (
            <div>
              <label style={label}>Passwort bestätigen</label>
              <input
                type="password" value={confirm} onChange={e => setConfirm(e.target.value)}
                placeholder="••••••••" required
                style={input}
              />
            </div>
          )}

          {error && (
            <div style={{
              padding: '10px 14px', borderRadius: 10,
              background: 'color-mix(in oklab, #ff5e8a 12%, transparent)',
              border: '1px solid color-mix(in oklab, #ff5e8a 30%, transparent)',
              color: '#ff5e8a', fontSize: 13, lineHeight: 1.4,
            }}>{error}</div>
          )}

          <button type="submit" disabled={loading} style={{
            padding: '13px 20px', marginTop: 4,
            background: loading ? 'oklch(0.27 0.03 285)' : '#aaff66',
            border: 0, borderRadius: 12,
            cursor: loading ? 'not-allowed' : 'pointer',
            fontFamily: "'Space Grotesk', system-ui", fontSize: 15, fontWeight: 700,
            color: loading ? 'oklch(0.68 0.022 285)' : '#0a1428',
            transition: 'all 150ms',
          }}>
            {loading ? 'Bitte warten…' : (isSignIn ? 'Anmelden' : 'Account erstellen')}
          </button>
        </form>

        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 12, color: 'oklch(0.5 0.02 285)' }}>
          {isSignIn ? (
            <>Noch kein Account?{' '}
              <button onClick={() => { setMode('signup'); setError(null); }} style={{
                background: 'none', border: 0, color: '#aaff66', cursor: 'pointer',
                fontSize: 12, fontWeight: 600, padding: 0, fontFamily: 'inherit',
              }}>Jetzt registrieren</button>
            </>
          ) : (
            <>Schon registriert?{' '}
              <button onClick={() => { setMode('signin'); setError(null); }} style={{
                background: 'none', border: 0, color: '#aaff66', cursor: 'pointer',
                fontSize: 12, fontWeight: 600, padding: 0, fontFamily: 'inherit',
              }}>Anmelden</button>
            </>
          )}
        </div>
      </div>
    </div>
    </div>
  );
}

function friendlyError(code) {
  const msgs = {
    'auth/user-not-found':      'Kein Account mit dieser E-Mail gefunden.',
    'auth/wrong-password':      'Falsches Passwort.',
    'auth/email-already-in-use':'Diese E-Mail ist bereits registriert.',
    'auth/invalid-email':       'Ungültige E-Mail-Adresse.',
    'auth/weak-password':       'Passwort ist zu schwach (mind. 6 Zeichen).',
    'auth/too-many-requests':   'Zu viele Versuche. Bitte kurz warten.',
    'auth/network-request-failed': 'Netzwerkfehler. Bitte Verbindung prüfen.',
  };
  return msgs[code] || 'Fehler: ' + code;
}

Object.assign(window, { AuthScreen });
