How can I make the camera rotate with gyroscope appropriately?

I want the camera to rotate 360º degrees using the gyroscope. I have this code:

void Awake() {
        Input.gyro.enabled = true;
    }

void Update() {
        transform.rotation = Input.gyro.attitude;
        transform.Rotate(0f, 0f, 180f, Space.Self);
        transform.Rotate(90f, 180f, 0f, Space.World);
    }

Which works fine if I don’t care about the camera having a starting rotation. But I actually want the camera to start looking with the rotation associated with the camera preview. I want it to start looking at something, and then start gyroscoping from there. So I changed the code a bit to this:

   void Awake() {
        Input.gyro.enabled = true;
    }

   void Start() {
        offset = transform.rotation * Quaternion.Inverse(GyroToUnity(Input.gyro.attitude));
    }

  void Update() {
     transform.rotation = offset * GyroToUnity(Input.gyro.attitude);
  }

  private static Quaternion GyroToUnity(Quaternion q) {
    return new Quaternion(q.x, q.y, -q.z, -q.w);
  }

Now it starts looking at the right place, but when I start moving the phone around the camera rotation gets funky, it starts turning upside down. I don’t know what to do, I searched everywhere. I tried this and this. Thank you for your time.

BUMP BUMP

You can use a Unity Asset called “Sensor Camera” which uses a Motion Sensor (Gyroscope/Accelerometer) on the player’s mobile device to control the game camera from a first-person view (just like in FPS Games).