<template>
  <form class="login-form-view lofty-reset-style" @submit.prevent="submit">
    <div v-show="type==='register'">
      <p class="sign-title">{{ title }}</p>
      <div class="sign-desc">{{loginSetting.description}}</div>
      <div class="form-label mt20">Full Name <span v-if="loginSetting.fullNameRequired" class="red">*</span></div>
      <input v-model="form.fullName" type="text" class="input-item" :class="{'lofty-error-field': error.fullName}" placeholder="Full Name" maxlength="50">
      <p v-show="error.fullName" class="lofty-error-msg">{{error.fullName}}</p>
      <div class="form-label mt20">Email <span class="red">*</span></div>
      <input v-model="form.account" type="text" inputmode="email" class="input-item" :class="{'lofty-error-field': error.account}" placeholder="Email*" name="account" maxlength="300">
      <p v-show="error.account" class="lofty-error-msg">{{error.account}}</p>
      <div class="form-label mt20">Phone <span v-if="loginSetting.phoneNumberRequired"  class="red">*</span></div>
      <input v-model="form.phoneNumber" type="tel" inputmode="tel" class="input-item" :class="{'lofty-error-field': error.phoneNumber}" placeholder="Phone (Used as your password)" name="phoneNumber">
      <p v-show="error.phoneNumber" class="lofty-error-msg">{{error.phoneNumber}}</p>
    </div>
    <div v-show="type==='login'">
      <p class="sign-title">{{ title }}</p>
      <div class="form-label mt10">Email <span class="red">*</span></div>
      <input v-model="form.account" type="text" class="input-item" :class="{'lofty-error-field': error.account}" placeholder="Email*" name="account" maxlength="300">
      <p v-show="error.account" class="lofty-error-msg">{{error.account}}</p>
      <div class="form-label mt20 password-label">
        <div>Password <span class="red">*</span></div>
        <a class="lofty-a-link" href="/pwreset/?pageKey=pwreset&lofty_page=pwreset" rel="noopener noreferrer">Forgot?</a>
      </div>
      <div class="password-container">
        <input v-model="form.password" :type="passwordType" class="input-item" :class="{'lofty-error-field': error.password}" placeholder="The initial password is phone number" name="password">
        <i v-show="form.password" class="lofty_iconfont lofty-icon-cancel_02" @click="form.password = ''"></i>
        <i v-show="passwordType==='password'" class="lofty_iconfont lofty-icon-password" @click="passwordType = 'text'"></i>
        <i v-show="passwordType==='text'" class="lofty_iconfont lofty-icon-view-active" @click="passwordType = 'password'"></i>
      </div>
      <p v-show="error.password" class="lofty-error-msg">{{error.password}}</p>
    </div>
    <div v-if="disclaimer && type==='register'" class="disclaimer-container">
      <Checkbox v-model="agreePolicy"/>
      <span v-html="disclaimer" class="policy-text"></span>
    </div>
    <button type="submit" class="submit-button lofty-btn" :disabled="disabledSubmit">
      {{ loginSetting.buttonText }}
    </button>
    <div v-if="loginSetting.googleLogin || loginSetting.facebookLogin">
      <div class="divider"><span>Or</span></div>
      <div class="third-party-login">
        <img v-if="loginSetting.facebookLogin" id="fb-div" :src="FacebookSvg" alt="facebook"/>
        <div v-if="loginSetting.googleLogin" class="google-btn-container">
          <img style="pointer-events: none" :src="GoogleSvg" alt="google"/>
          <div id="gmail-div"></div>
        </div>
      </div>
    </div>
    <div class="change-login-type">
      <div v-show="type==='register'">Already have an account? <span class="lofty-link" @click="type='login'">Sign In</span></div>
      <div v-show="type==='login'">New here? <span class="lofty-link" @click="type='register'">Create an account</span></div>
    </div>
  </form>
</template>

<script setup>
import Checkbox from '@/components/checkbox/index.vue';
import util from "@/util"
import { userState } from '@/common/sign-log/user.js';
import getDefault from '@/admin/leadCaptureSetting/basicSetting/defaultSetting.js'
import http from '@/api';
import FacebookSvg from "@/static/facebook.svg";
import GoogleSvg from "@/static/google.svg";
import { useGoogle } from "@/hooks/useGoogle.js";
import { useFacebook } from "@/hooks/useFacebook.js";
import { isEmailValid, isPhoneValid } from '@/common/reg-verify.js';
const { callback, account, formType } = defineProps({ callback : Function, account: String, formType: String })
const loginSetting = userState.commonData.loginSetting || getDefault()
const type = ref(formType || 'register')
const passwordType = ref('password')
const title = computed(()=> type.value === 'login' ? 'SIGN IN': loginSetting.title);
const disclaimer = userState.commonData.disclaimerHtml || ''
const disclaimerRequired = userState.commonData.disclaimerRequired ?? true
const agreePolicy = ref(false)
const disabledSubmit = computed(()=> !!disclaimer && disclaimerRequired && !agreePolicy.value && type.value === 'register')

function submit() {
  if(type.value === 'login') {
    login()
  } else {
    register();
  }
}
const form = reactive({
  fullName: '',
  account: account || '',
  phoneNumber: '',
  password: '',
  roles: ''
})
async function register() {
  if (loginSetting.fullNameRequired && !form.fullName) {
    error.fullName = errorMsg
    resetError()
    return
  }
  if (loginSetting.phoneNumberRequired && !form.phoneNumber) {
    error.phoneNumber = errorMsg
    resetError()
    return
  }
  if (verifyEmail()) {
    const passed = await verifyPhone()
    if (passed) {
      const [firstName, lastName] = (form.fullName || '').split(' ', 2)
      const currentListing = window.__loftyCurrentListing__
      const data = {
        firstName,
        lastName: lastName || '',
        account: form.account,
        phoneNumber: form.phoneNumber,
        roles: getRole(),
        // listing detail 页面注册时附带 listingId + sold，homethy 端 SiteRegisterService
        // .listingInfoHandler 反查 listing 详情自动填 CRM lead 的 Property Address，跟
        // site-cms 主链路一致（AM-584538）。pageUrl 用作 landing page 关联。
        pageUrl: window.location.href,
        ...(currentListing?.listingId ? {
          listingId: String(currentListing.listingId),
          isSold: Boolean(currentListing.sold),
        } : {}),
        ...(disclaimer ? { agreementInfo: { consentGiven: agreePolicy.value } } : {})
      }
      const res = await http.post(`/register/leadRegister`, { data })
      if (res.data?.user) {
        userState.user.value = res.data.user
        let [msg,time] = ['Registered Successfully！',3000]
        if(!form.phoneNumber) {
          msg += 'Your initial password has been sent to your email. Please check your inbox.'
          time = 6000
        }
        util.toast(msg, time)
        util.executeSubmitJS(loginSetting.submitJs)
        callback && callback()
      } else if (res.status.code === 210003) {
        util.toast(res.status.msg, 3000)
        type.value = 'login'
      }
    }
  }
}
async function login() {
  if(verifyEmail() && verifyPassword()) {
    await util.addScript(LoftyIdxUtils.public_url("js/md5.min.js"), true);
    const data = {
      account: form.account,
      password: window.md5(form.password)
    }
    const res = await http.post(`/register/login-wp`, { data })
    if(res.data?.user) {
      userState.user.value = res.data.user
      util.toast('Login Successfully', 3000)
      callback && callback()
    } else {
      util.toast(res.status.msg, 3000)
    }
  }
}
const errorMsg = "Please fill out this field.";
const error = reactive({
  fullName: '',
  account: '',
  phoneNumber: '',
  password: ''
})
function resetError() {
  setTimeout(()=>{
    Object.keys(error).forEach((key) => {error[key] = ''})
  }, 5000)
}
function verifyEmail() {
  const { account } = form
  error.account = !account ? errorMsg : (!isEmailValid(account)? 'Email invalid' : '')
  resetError()
  return isEmailValid(account)
}
async function verifyPhone() {
  const { phoneNumber } = form
  if (loginSetting.phoneNumberRequired || !!phoneNumber) {
    if(!isPhoneValid(phoneNumber)) {
      error.phoneNumber = 'Phone invalid'
      resetError()
      return false
    }
    const res = await http.get(`/register/phoneValidate?phoneNumber=${phoneNumber}`)
    if(res.status.code === 0) {
      return true
    } else {
      error.phoneNumber = res.status.msg
      resetError()
      return false
    }
  }
  return true
}
function verifyPassword() {
  const { password } = form
  error.password = !password ? errorMsg : ''
  resetError()
  return !!password
}
function getRole() {
  let role = '2'
  if(window.__loftyCurrentListing__?.sold) {
    role = '1'
  }
  if(isRenter()) {
    role = '5'
  }
  return role
}
function isRenter() {
  return [...document.querySelectorAll("span.lofty-value")].find(span => span.textContent.trim() === "For Rent")
}

onMounted(initThreePartyLogin);
function initThreePartyLogin() {
  const { googleLogin, facebookLogin, googleClientId, facebookClientId } = loginSetting
  if (googleLogin) {
    useGoogle(googleClientId, (user) => {
      threePartyLogin(user)
    });
  }
  if(facebookLogin) {
    useFacebook(facebookClientId, (user) => {
      user.from = 'FACEBOOK';
      threePartyLogin(user)
    })
  }
}

async function threePartyLogin(user) {
  user.roles = getRole();
  const res = await http.post(`/register/thirdParty/loginOrRegister`, { data: user })
  if (res.data?.user) {
    userState.user.value = res.data.user
    util.toast(res.data.existUser ? 'Login Successfully' : 'Registered Successfully', 3000)
    if (!res.data.existUser) {
      util.executeSubmitJS(loginSetting.submitJs);
    }
    callback && callback()
  } else {
    util.toast(res.status.msg, 3000)
  }
}

</script>
<style lang="scss">
.login-form-view {
  width: 400px;
  padding: 30px;
  background: #fff;
  @media (max-width: 600px) {
    width: calc(100vw - 30px);
    padding: 15px;
    margin: 0 auto;
  }
  .lofty-a-link{
    color: rgb(76, 132, 255);
  }
  .sign-title {
  font-size: 22px;
  font-weight: 700;
  font-family: 'font-play-bold';
  line-height: 33px;
  margin-bottom: 0;
  text-align: center;
  color: rgb(25,25,25);
}
.sign-desc {
  margin-top: 15px;
  text-align: center;
  font-family: 'font-regular';
  font-size: 12px;
  line-height: 18px;
  color: rgb(80, 80, 80);
}

.input-item {
  margin-top: 10px;
  border: 1px solid #dadada;
  outline: none;
  height: 40px;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 0;
  transition: all 0.3s;
  &:focus {
    border-color: #111;
  }
  &::placeholder {
    color: rgb(168, 168, 168);
  }
}
.lofty-error-field {
  border-color: #fb4444;
}
.lofty-error-msg {
  margin: 5px 0 0 0;
  line-height: 15px;
  font-size: 12px;
  color: #fb4444;
}
.form-label {
  font-family: 'font-regular';
  font-size: 14px;
  color: rgb(80, 80, 80);
  line-height: 21px;
  .red {
    color: rgba(240, 69, 76, 1);
  }
  &.password-label{
    display: flex;
    justify-content: space-between;
    align-items: center;
    a{
      font-size: 14px;
    }
  }
}
.password-container {
  position: relative;
  .lofty_iconfont {
    position: absolute;
    cursor: pointer;
    top: 22px;
    color: rgb(168, 168, 168);
  }
  .lofty-icon-cancel_02 {
    right: 35px;
  }
  .lofty-icon-password, .lofty-icon-view-active {
    right: 10px;
  }
}
.disclaimer-container {
  margin-top: 20px;
  display: flex;
  .policy-text {
    margin-left: 10px;
    font-size: 12px;
    line-height: 18px;
    font-family: 'font-regular';
    color: rgb(168, 168, 168);
  }
}
.submit-button {
  height: 40px;
  font-size: 14px;
  font-weight: 700;
  line-height: 38px;
  text-align: center;
  margin-top: 20px;
  border: 0;
  width: 100%;
  padding: 0;
  cursor: pointer;
}
.divider {
  display: flex;
  align-items: center;
  text-align: center;
  margin-top: 16px;
  &::before, &::after {
    content: "";
    flex: 1;
    border-bottom: 1px solid #ddd;
  }
  > span {
    color: rgb(168, 168, 168);
    font-size: 12px;
    margin: 0 8px;
  }
}
.third-party-login {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30px;
  margin-top: 10px;
  position: relative;
  img {
    cursor: pointer;
    width: 30px;
    height: 30px;
    z-index: 2;
    position: relative;
  }
  .google-btn-container {
    position: relative;
    height: 30px;
    #gmail-div {
      position: absolute;
      left: 0;
      top: 0;
      width: 30px;
      height: 30px;
      z-index: 1;
      opacity: 0;
      cursor: pointer;
    }
  }
}
.change-login-type {
  margin-top: 10px;
  text-align: center;
  font-family: 'font-regular';
  font-size: 14px;
  color: rgb(80,80,80);
}
}

</style>
