// Saladizer Web — Auth screen (login + register + Google + forgot pw).

function AuthScreen({ lang, onAuthenticated }) {
  const isAr = lang === 'ar';
  const [mode, setMode] = React.useState('login'); // 'login' | 'register'
  const [email, setEmail] = React.useState('');
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const googleBtnRef = React.useRef(null);

  const tx = isAr ? {
    welcome: 'مرحباً بك في Saladizer',
    sub: 'سجّل دخولك لحفظ سلطاتك ومتابعة أهدافك.',
    login: 'تسجيل دخول',
    register: 'حساب جديد',
    email: 'البريد الإلكتروني',
    username: 'اسم المستخدم',
    password: 'كلمة المرور',
    submitLogin: 'دخول',
    submitRegister: 'إنشاء الحساب',
    toRegister: 'ما عندك حساب؟ سجّل الآن',
    toLogin: 'عندك حساب؟ سجّل دخول',
    or: 'أو',
    busy: 'جارٍ المعالجة...',
    forgot: 'نسيت كلمة المرور؟',
    google: 'المتابعة بحساب جوجل',
  } : {
    welcome: 'Welcome to Saladizer',
    sub: 'Sign in to save your bowls and track your macros.',
    login: 'Sign in',
    register: 'Create account',
    email: 'Email',
    username: 'Username',
    password: 'Password',
    submitLogin: 'Sign in',
    submitRegister: 'Create account',
    toRegister: "Don't have an account? Sign up",
    toLogin: 'Have an account? Sign in',
    or: 'or',
    busy: 'Working...',
    forgot: 'Forgot password?',
    google: 'Continue with Google',
  };

  async function submit(e) {
    e.preventDefault();
    setErr('');
    setBusy(true);
    try {
      let out;
      if (mode === 'login') {
        out = await window.api.login(email.trim(), password);
      } else {
        out = await window.api.register(email.trim(), username.trim(), password);
      }
      if (out && out.user) onAuthenticated(out.user);
    } catch (e2) {
      const msg = (e2 && (e2.data?.message || e2.data?.error || e2.message)) || (isAr ? 'حدث خطأ' : 'Something went wrong');
      setErr(String(msg));
    } finally {
      setBusy(false);
    }
  }

  // Google Identity Services — render the official button when GSI is loaded.
  // The Google client ID is read from a window-level config that the server can
  // inject. If absent, we hide the Google button.
  const clientId = (typeof window !== 'undefined' && window.GOOGLE_CLIENT_ID) || '';

  React.useEffect(() => {
    if (!clientId) return;
    let cancelled = false;
    function tryInit() {
      if (cancelled) return;
      if (!(window.google && window.google.accounts && window.google.accounts.id) || !googleBtnRef.current) {
        setTimeout(tryInit, 200);
        return;
      }
      try {
        window.google.accounts.id.initialize({
          client_id: clientId,
          callback: async (resp) => {
            if (!resp || !resp.credential) return;
            setBusy(true); setErr('');
            try {
              const out = await window.api.googleLogin(resp.credential);
              if (out && out.user) onAuthenticated(out.user);
            } catch (e2) {
              const msg = (e2 && (e2.data?.error || e2.message)) || (isAr ? 'تعذّر الدخول عبر جوجل' : 'Google sign-in failed');
              setErr(String(msg));
            } finally {
              setBusy(false);
            }
          },
        });
        window.google.accounts.id.renderButton(googleBtnRef.current, {
          theme: 'outline',
          size: 'large',
          width: 320,
          text: 'continue_with',
        });
      } catch (e2) {
        console.warn('[Saladizer] GSI init failed:', e2);
      }
    }
    tryInit();
    return () => { cancelled = true; };
  }, [clientId, isAr]);

  return (
    <div className="auth-screen">
      <div className="auth-card">
        <div className="auth-brand">
          <img src="assets/saladizer-logo-full.png" alt="Saladizer" />
        </div>
        <h1 className="auth-title">{tx.welcome}</h1>
        <p className="auth-sub">{tx.sub}</p>

        <form onSubmit={submit} className="auth-form">
          <label className="auth-label">
            <span>{tx.email}</span>
            <input
              type="email"
              required
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
            />
          </label>

          {mode === 'register' && (
            <label className="auth-label">
              <span>{tx.username}</span>
              <input
                type="text"
                required
                autoComplete="username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="username"
                minLength={3}
              />
            </label>
          )}

          <label className="auth-label">
            <span>{tx.password}</span>
            <input
              type="password"
              required
              autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              minLength={6}
            />
          </label>

          {mode === 'login' ? (
            <div style={{ textAlign: 'end', marginTop: -4 }}>
              <a className="link" href="/forgot-password" target="_blank" rel="noreferrer">
                {tx.forgot}
              </a>
            </div>
          ) : null}

          {err ? <div className="auth-error">{err}</div> : null}

          <button type="submit" className="btn btn-primary auth-submit" disabled={busy}>
            {busy ? tx.busy : (mode === 'login' ? tx.submitLogin : tx.submitRegister)}
          </button>
        </form>

        {clientId ? (
          <>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              margin: '18px 0 12px', color: 'var(--fg-muted)', fontSize: 12,
            }}>
              <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
              <span>{tx.or}</span>
              <div style={{ flex: 1, height: 1, background: 'var(--border)' }} />
            </div>
            <div ref={googleBtnRef} style={{ display: 'flex', justifyContent: 'center' }} />
          </>
        ) : null}

        <div className="auth-switch">
          {mode === 'login' ? (
            <button type="button" className="link" onClick={() => { setErr(''); setMode('register'); }}>
              {tx.toRegister}
            </button>
          ) : (
            <button type="button" className="link" onClick={() => { setErr(''); setMode('login'); }}>
              {tx.toLogin}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen });
