<template>
  <section class="section">
    <h2 class="section__title">Your information</h2>
    <div class="gosubs-form">
      <div class="gosubs-form__row">
        <div class="gosubs-form__column">
          <div 
            class="gosubs-form__group" 
            :class="{ 
              filled: (isFilled === 'first_name') || (subscription.first_name),
              error: errors.first_name
            }"
          >
            <label for="first_name" class="gosubs-form__label">First Name</label>
            <input
              id="first_name"
              data-remote-name="first_name"
              @focus="isFilled = 'first_name'"
              @blur="validateForm"
              class="gosubs-form__input"
              type="text"
              v-model="subscription.first_name"
            />
            <span v-if="errors.first_name" class="gosubs-form__error">
              {{ errorMessage('First Name', errors.first_name[0]) }}
            </span>
          </div>
        </div>

        <div class="gosubs-form__column">
          <div 
            class="gosubs-form__group"
            :class="{
              filled: (isFilled === 'last_name') || (subscription.last_name),
              error: errors.last_name
            }">
            <label for="last_name" class="gosubs-form__label">Last Name</label>
            <input
              id="last_name"
              data-remote-name="last_name"
              @focus="isFilled = 'last_name'"
              @blur="validateForm"
              class="gosubs-form__input"
              type="text"
              v-model="subscription.last_name"
            />
            <span v-if="errors.last_name" class="gosubs-form__error">
              {{ errorMessage('Last Name', errors.last_name[0])}}
            </span>
          </div>
        </div>

      </div>

      <div class="gosubs-form__row">
        <div
        class="gosubs-form__group gosubs-form__group--selectbox"
        :class="{
          filled: (isFilled === 'devices_input') || (subscription.material_id > 0),
          error: errors.material
        }">
          <label for="devices_input" class="gosubs-form__label">Select your device</label>
          <select
            @focus="isFilled = 'devices_input'"
            @blur="validateForm"
            data-remote-name="material"
            class="gosubs-form__input"
            id="devices_input"
            name="Devices"
            v-model="subscription.material_id"
          ><option v-for="{ id, public_name } in sortedMaterials"
              :key="id"
              :value="id"
            >{{ public_name }}</option>
          </select>
          <div class="gosubs-form__arrow">
            <svg width="608" height="320" viewBox="0 0 608 320" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M0 15.9998C0 11.9048 1.562 7.81075 4.687 4.68675C10.935 -1.56225 21.066 -1.56225 27.314 4.68675L304 281.373L580.687 4.68675C586.935 -1.56225 597.066 -1.56225 603.314 4.68675C609.562 10.9358 609.563 21.0657 603.314 27.3137L315.314 315.314C309.066 321.563 298.935 321.563 292.687 315.314L4.687 27.3137C1.562 24.1887 0 20.0948 0 15.9998H0Z" fill="#555555"/>
            </svg>
          </div>
          <span v-if="errors.material" class="gosubs-form__error">
            {{ errorMessage('Device', errors.material[0])}}
          </span>
        </div>
      </div>
      <div class="gosubs-form__row">
        <div
          class="gosubs-form__group"
          :class="{
            filled: (isFilled === 'email_input') || (subscription.email),
            error: errors.email
          }">
          <label for="email_input" class="gosubs-form__label">Email</label>
          <input
            @focus="isFilled = 'email_input'"
            @blur="validateForm"
            id="email_input"
            data-remote-name="email"
            class="gosubs-form__input"
            type="email"
            v-model="subscription.email"
          >
          <span v-if="errors.email" class="gosubs-form__error">
            {{ errorMessage('Email', errors.email[0]) }}
          </span>
        </div>
      </div>
      <div class="braintree__security">
        <i class="icon icon_lock"></i>
        We will be customising your phone case to your style and for that, we need an active communication channel with you. Hence, we request this information. Your privacy will be fully protected. That's a promise.
      </div>
      <button @click="validateForm" class="button button--cta">Proceed</button>
    </div>
  </section> 
</template>

<script>

const subscription = { material_id: '' };

const localErrorMessages = {
  "can't be blank": "is required",
  "must exist": "is required",
  "has already been taken": "is already in use"
}

export default {
  data() {
    return {
      loaded: false,
      active: false,
      subscription: subscription,
      maxRetries: 16,
      currentRetries: 1,
      timeoutId: null,
      errors: {},
      isFilled: '',
      localErrorMessages: localErrorMessages
    }
  },
  props: {
    program: {
      type: Object,
      default: () => {
        return { materials: [] }
      }
    }
  },
  methods: {
    validateForm(e) {
      this.$axios.post(
        `${process.env.VUE_APP_GOSUBS_HOST}/api/subscription-valid/`,
        { subscription: this.formattedSubscription }
      )
      .then( (r) => {
        if (r.data.valid)
          this.subscription.stripeInfo = r.data.stripe_customer
        if (e.type === "blur"){
          let targetRemoteName = e.target.attributes['data-remote-name'].value
          this.errors[targetRemoteName] = r.data.errors[targetRemoteName]
          this.$forceUpdate()
        } else {
          this.errors = r.data.errors;
          if (r.data.valid) {
            this.active = true;
            this.klaviyoLead();
            this.$emit('submitsubscription', { subscription: this.subscription })
          }
        }
        this.$emit('updatesubscription', { valid: r.data.valid, subscription: this.subscription })
      });
    },

    klaviyoLead() {
      this.$axios.post(
        `${process.env.VUE_APP_GOSUBS_HOST}/api/klaviyo-lead/`,
        { subscription: this.formattedSubscription }
      )
    },

    errorMessage(field, message) {
      return field + ' ' + (this.localErrorMessages[message] || message)
    }
  },
  computed: {
    programCode() {
      return this.$route.params.program_code;
    },
    formattedSubscription() {
      return { ...this.subscription, program_id: this.program.id }
    },
    sortedMaterials() {
      const materials = this.program.materials
      const positions = [/iphone/i, /samsung/i, /.huawei/i, /google/i]
      const sorted = []
      positions.forEach((materialPosition) => {
        materials.forEach((material) => {
          if (material.public_name.match(materialPosition))
            sorted.push(material)
        })
      })
      materials.forEach((material) => {
        if(!sorted.find((dupMaterial) => dupMaterial.id === material.id))
          sorted.push(material)
      })
      return sorted
    }
  },
  watch: {
    active(newVal) {
      if (newVal) {
        const widget = document.querySelector('#stamped-main-widget')
        if (widget) widget.style.display = 'none'
      }
    }
  },
  name: 'SubscriptionForm'
}
</script>

<style lang="scss">
.gosubs-form__row {
  margin-bottom: 4 * $gutter;
  display: flex;
  justify-content: space-between;
  position: relative;
}

.gosubs-form__column {
  width: calc(50% - 8px);
  box-sizing: border-box;
}

.gosubs-form__group {
  width: 100%;
  position: relative;
}

.gosubs-form__group.filled .gosubs-form__label{
  font-size: 12px;
  top: 14px;
  transition: .2s ease all;
}

.gosubs-form__group.error .gosubs-form__input{
  background-color: #fef0f0;
  border: 1px solid #f08080;
}

.gosubs-form__group.error .gosubs-form__label{
  display: none;
}

.gosubs-form__group.filled .gosubs-form__input{
  padding-top: 20px;
}

.gosubs-form__group--selectbox .gosubs-form__input {
  padding-top: 20px;
  line-height: 19px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.gosubs-form__arrow {
  position: absolute;
  top: 50%;
  right: 15px;
  width: 12px;
  display: block;
  transform: translateY(-50%);
}

.gosubs-form__arrow svg{
  max-width: 100%;
  height: auto;
}

.gosubs-form .gosubs-form__error {
  position: absolute;
  left: 10px;
  top: 9px;
  font-size: 12px;
  margin: 0;
  padding: 0;
  background: 0 0;
  height: 13px;
  line-height: 13px;
  text-transform: none;
  color: #f08080;
}

.gosubs-form .gosubs-form__label {
  position: absolute;
  left: 17px;
  top: 27px;
  font-size: 14px;
  transform: translateY(-50%);
  height: 11px;
  line-height: 12px;
  margin: 0;
  padding: 0;
  background: 0 0;
  cursor: pointer;
  text-transform: none;
  transition: .2s ease all;
}

.gosubs-form .gosubs-form__input {
  background-color: $color_gray;
  border: 1px solid transparent;
  border-radius: 12px;
  color: $color_title;
  font-size: 14px;
  line-height: normal;
  padding: 3*$gutter $gutter_mobile 0;
  width: 100%;
  height: 56px;
  outline: none;
  transition: .2s ease all;
  box-sizing: border-box;
}
.gosubs-form .gosubs-form__input:focus {
  outline: none;
  border-color: #333;
  padding-top: 24px;
  background: #fff
}

.gosubs-form .gosubs-form__input::placeholder{
  font-size: 12px;
}

.gosubs-form {
  display: grid;
}
.gosubs-title {
  text-align: center;
  margin: 20px 0;
}

.button {
  background-color: $color_primary;
  height: 56px;
  width: 100%;
  border-radius: 12px;
  border: 1px solid $color_gray;
  color: #fff;
  padding: 0 $gutter_mobile;
  margin-bottom: $gutter_mobile;
  outline: none;

  &:hover {
    background-color: $color_title;
  }

  span {
    color: white;
  }
}

.success__icon {
  position: relative;
  padding: 30px;
  display: table;
  margin: 0 auto 30px;
}

.braintree__security {
  color:#999;
  font-size:13px;
  line-height:16px;
  min-height:20px;
  position:relative;
  margin-bottom:30px;
}

.lds-dual-ring {
  display: inline-block;
  width: 80px;
  height: 80px;
}
.lds-dual-ring:after {
  content: " ";
  display: block;
  width: 64px;
  height: 64px;
  margin: 8px;
  border-radius: 50%;
  border: 6px solid #000;
  border-color: #000 transparent #000 transparent;
  animation: lds-dual-ring 1.2s linear infinite;
}

@keyframes lds-dual-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

  @keyframes rotate {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  @keyframes grow {
    0%, 100% {
      transform: scale(0);
    }
    50% {
      transform: scale(1);
    }
  }
  @keyframes checkmark {
    0%, 100% {
      transform: scale(0);
    }
    10%, 50%, 90% {
      transform: scale(1);
    }
  }
</style>
###################################