class GoogleSSOPage < UniversalPage
  h1(:heading, id: "headingText")
  div(:next_button) do
    span_element(text: "Next").parent
  end
  text_field(:email, type: "email")
  text_field(:password, type: "password")
  text_field(:enter_code, "aria-label": "Enter code")
  div(:lang_selector, "aria-haspopup": "listbox")
  element(:us_language, css: 'li[data-value="en"]')

  def set_language_to_us_english
    return unless lang_selector_element
                  .div_element('aria-selected': "true", 'data-value': "en").present? == false
    lang_selector_element.click
    wait_until { us_language_element.present? }
    us_language_element.click
  end

  def google_sso_login(email, password, authenticator_key)
    set_language_to_us_english
    if heading_element.text.downcase == "sign in"
      login_with_authenticator(email, authenticator_key, password)
    else
      choose_account(email)
    end
  end

  def login_with_authenticator(email, authenticator_key, password)
    self.email = email
    next_button_element.click
    self.password = password
    next_button_element.click
    wait_until { heading_element.text.downcase == "2-step verification" }
    otp = Support::OtpGenerator.generate_otp(authenticator_key)
    self.enter_code = otp
    begin
      retries ||= 0
      next_button_element.when_present.click
    rescue Selenium::WebDriver::Error::ElementClickInterceptedError
      retry if (retries += 1) < 3
    end
  end

  def choose_account(google_account)
    div_element(id: "profileIdentifier", text: google_account).click
  end
end
