// Auth state + login screen for Earl OS.
// Uses Supabase Google OAuth. All other components read window._session.

function useAuth() {
  const [session, setSession] = React.useState(undefined); // undefined = loading

  React.useEffect(() => {
    _sb.auth.getSession().then(({ data: { session } }) => setSession(session));
    const { data: { subscription } } = _sb.auth.onAuthStateChange((_e, session) => {
      setSession(session);
    });
    return () => subscription.unsubscribe();
  }, []);

  return session;
}

function LoginScreen() {
  const [busy, setBusy] = React.useState(false);

  const signIn = async () => {
    setBusy(true);
    await _sb.auth.signInWithOAuth({
      provider: 'google',
      options: {
        redirectTo: window.location.origin,
        scopes: 'https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/calendar.readonly',
      },
    });
  };

  return (
    <div className="login-bg">
      <div className="login-card">
        <img src="assets/earl-neal-logo.jpeg" className="login-logo" alt="EN" />
        <div className="login-brand">EARL OS</div>
        <div className="login-tagline">Planning · Production · Execution</div>
        <button className="login-btn" onClick={signIn} disabled={busy}>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
            <path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" fill="#34A853"/>
            <path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/>
            <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
          </svg>
          {busy ? 'Redirecting…' : 'Sign in with Google'}
        </button>
        <div className="login-note">Your data stays private — only you can access it.</div>
      </div>
    </div>
  );
}

// Expose so app.jsx can use them
Object.assign(window, { useAuth, LoginScreen });
