{% extends "users/layout.html" %}

{% block head %}
  {{ super() }}
  {% if app.extensions.frasco_users.options['recaptcha_key'] %}
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  {% endif %}
  {% if app.extensions.frasco_users.options['hcaptcha_key'] %}
  <script src="https://hcaptcha.com/1/api.js" async defer></script>
  {% endif %}
{% endblock %}

{% block users_title %}{% endblock %}

{% block users_nav %}<a href="{{url_for('.login', oauth=request.args.get('oauth'), next=request.args.get('next'))}}">{{_("Login with existing account")}}</a>{% endblock %}

{% block users_content %}
<div class="signup-box">
  <form action="" method="post" id="signup-form" onsubmit="onFormSubmit(event)">
    {{ form.hidden_tag() }}
    <h2>{{_("Create an account")}}</h2>
    {% if is_oauth %}
    <div class="alert alert-info">
      <a href="{{url_for('.login', oauth=1, next=request.args.get('next'))}}" class="btn btn-info pull-right">{{_("Login now &raquo;")|safe}}</a>
      <strong>{{_("Already a member ?")}}</strong>
    </div>
    {% endif %}
    <div class="form-group">
      <label for="email" class="form-label">{{_("Your company email")}}</label>
      {{ form.email(class_="form-control form-control-lg", placeholder="you@company.com") }}
    </div>
    <div class="form-group">
      <label for="username" class="form-label">{{_("Create a username")}}</label>
      {{ form.username(class_="form-control form-control-lg", placeholder=_("No space allowed")) }}
      <div class="invalid-feedback">{{_("Username already taken")}}</div>
    </div>
    {% if must_provide_password %}
    <div class="form-group">
      <label for="password" class="form-label">{{_("Choose a password")}}</label>
      {{ form.password(class_="form-control form-control-lg", minlength=("1" if app.debug else "8"), placeholder=_("At least 8 chars.")) }}
    </div>
    {% endif %}
    <div class="form-group">
      {% if app.config['TERMS_URL'] or app.config['PRIVACY_URL'] %}
        <label class="form-check-label">
          {{ form.tos() }}
          {% if not app.config['PRIVACY_URL'] %}
          {{_("You agree to our <a href=\"{0}\" target=\"_blank\">Terms of Service</a>").format(get_localized_config_value(app.config['TERMS_URL']))|safe}}
          {% elif not app.config['TERMS_URL'] %}
          {{_("You agree to our <a href=\"{0}\" target=\"_blank\">Privacy Policy</a>").format(get_localized_config_value(app.config['PRIVACY_URL']))|safe}}
          {% else %}
          {{_("You agree to our <a href=\"{0}\" target=\"_blank\">Terms of Service</a> &amp; <a href=\"{1}\" target=\"_blank\">Privacy Policy</a>").format(get_localized_config_value(app.config['TERMS_URL']), get_localized_config_value(app.config['PRIVACY_URL']))|safe}}
          {% endif %}
        </label>
      {% endif %}
      {% if app.config['SIGNUP_NEWSLETTER'] %}
        <label>
          {{form.email_newsletter()}}
          {{form.email_newsletter.label.text}}
        </label>
      {% endif %}
    </div>
    {% if app.extensions.frasco_users.options['recaptcha_key'] %}
    <div class="g-recaptcha"
      data-sitekey="{{app.extensions.frasco_users.options['recaptcha_key']}}"
      data-callback="onRecaptchaResponse"
      data-size="invisible">
    </div>
    {% endif %}
    {% if app.extensions.frasco_users.options['hcaptcha_key'] %}
    <div id="hcaptcha" class="h-captcha"
      data-sitekey="{{app.extensions.frasco_users.options['hcaptcha_key']}}"
      data-callback="onRecaptchaResponse"
      data-size="invisible"></div>
    {% endif %}
    <div class="d-flex align-items-center">
      <div class="flex-fill">
        <button type="submit" class="btn btn-primary btn-lg mt-0">{{_("Create account &raquo;")|safe}}</button>
      </div>
      {% include "users/_sso_link.html" %}
    </div>
  </form>
  {% if THIRD_PARTY_ACCOUNT_PROVIDERS|length > 0 or request.args.get('invite') or (not request.args.get('hide_msg') and (app.config['PAYMENTS_ENABLED'] or app.config['SIGNUP_MESSAGE'])) %}
  <div class="promo">
    {% if not request.args.get('hide_msg') and not request.args.get('invite') and (app.config['PAYMENTS_ENABLED'] or app.config['SIGNUP_MESSAGE']) %}
      <p>
        {% if app.config['PAYMENTS_ENABLED'] %}
          {{ _("Start your free 15 days trial now. No credit card required and without any limitations.") }}
        {% else %}
          {{ get_localized_config_value(app.config['SIGNUP_MESSAGE'])|nl2br }}
        {% endif %}
      </p>
      <p class="mandatory-notice">
        {{_('All fields are mandatory')}}
      </p>
    {% endif %}
    {% if request.args.get('invite') %}
      <p>
        {{_('You have been invited to join Kantree. Use the same email you have been invited with.')}}
      </p>
      <p class="mandatory-notice">
        {{_('All fields are mandatory')}}
      </p>
    {% endif %}
    {% include "users/_external_auth.html" %}
  </div>
  {% endif %}
</div>

<script type="text/javascript">
  $(function() {
    var match = RegExp('[?&]email=([^&]*)').exec(window.location.search);
    if (match) {
      document.getElementById('email').value = decodeURIComponent(match[1].replace(/\+/g, ' '));
    }

    $('#password').passtrength({
      minChars: 8,
      passwordToggle: false,
      tooltip: false,
      textWeak: "{{_('Weak')}}",
      textMedium: "{{_('Medium')}}",
      textStrong: "{{_('Strong')}}",
      textVeryStrong: "{{_('Very Strong')}}"
    });

    let checkUsernameTimeout;
    $("#username").on('keypress', () => {
      if (checkUsernameTimeout) {
        clearTimeout(checkUsernameTimeout);
        checkUsernameTimeout = null;
      }
      checkUsernameTimeout = setTimeout(() => {
        var username = $('#username').val();
        if (!username) return;
        fetch("{{url_for('check_username_availability')}}?username=" + username).then(r => {
          r.json().then(data => {
            $('#username').toggleClass('is-valid', data.available);
            $('#username').toggleClass('is-invalid', !data.available);
            $('#signup-form button[type="submit"]')[0].disabled = !data.available;
          })
        });
      }, 500);
    });
  });

  function trackSignup() {
    {% if app.config['GOOGLE_ANALYTICS_ID'] %}
    ga('send', 'event', 'account', 'signup', 'saas');
    {% endif %}
    {% if app.config['PLAUSIBLE_URL'] %}
    plausible('signup');
    {% endif %}
  }
  function onFormSubmit(e) {
    {% if app.extensions.frasco_users.options['recaptcha_key'] %}
    e.preventDefault();
    grecaptcha.execute();
    {% elif app.extensions.frasco_users.options['hcaptcha_key'] %}
    e.preventDefault();
    hcaptcha.execute();
    {% else %}
    trackSignup();
    {% endif %}
  }
  function onRecaptchaResponse() {
    trackSignup();
    document.getElementById("signup-form").submit();
  }

  {% if app.extensions.frasco_users.options['validate_password_regexps'] %}
  $(function() {
    $('input[type="password"]').popover({
      content: "{{app.extensions.frasco_users.options['validate_password_regexps']|map('last')|join('<br>')|safe}}",
      html: true,
      placement: 'top',
      trigger: 'focus'
    });
  });
  {% endif %}
</script>
{% endblock %}

{% block footer %}
  {{ super() }}
  {% include "users/_tracking_scripts.html" %}
{% endblock %}
