<template>
  <div v-if="isMobile" class="lofty-mobile-fix-bottom lofty-request-tour-mobile">
    <div class="get-touch-submit-btn" @click="openMessagePop">GET IN TOUCH</div>
    <div class="lofty-btn schedule-tour-lofty" @click="openSchedulePop" v-if="!sold">Schedule a Tour</div>
  </div>
  <div v-else :style="{position: position}" class="lofty-right-panel">
    <template v-if="!sold">
      <div v-if="!isScheduled" class="lofty-request-tour lofty-right-container">
        <div class="title">
          REQUEST A TOUR
          <Tooltip>
            <template #trigger>
              <span class="lofty_iconfont lofty-icon-help"></span>
            </template>
            <template #content>
            <span class="help-tip">
               If you would like to see this home without being there in person, select the "Virtual Tour" option and your agent will contact you to discuss available opportunities.
            </span>
            </template>
          </Tooltip>
        </div>
        <div class="lofty-tour-type-tab">
          <div class="tab-type" :class="{active: tourType === 'tour_info'}" @click="tourType='tour_info'">In-Person</div>
          <div class="tab-type" :class="{active: tourType === 'virtual_tour'}" @click="tourType='virtual_tour'">Virtual Tour</div>
        </div>
        <swiper-calendar class="lofty-swiper-calendar" :id="id"></swiper-calendar>
        <div class="lofty-btn schedule-tour-lofty" @click="openSchedulePop">Schedule a Tour</div>
      </div>

      <div v-else class="is-scheduled lofty-right-container">
        <div class="title">Your Request was Received!</div>
        <div class="scheduled-desc">We'll be in touch to confirm our meeting</div>
        <div class="scheduled-date">{{formatDate(scheduleInfo.startTime)}}</div>
        <div class="scheduled-time">{{ dateFormat('hh:mmp', scheduleInfo.startTime) }} - {{ dateFormat('hh:mmp', scheduleInfo.endTime) }}</div>
        <div class="lofty-btn schedule-tour-lofty" @click="openSchedulePop(true)">Schedule Again</div>
      </div>
    </template>

    <div class="get-touch lofty-right-container">
      <div class="title">GET IN TOUCH</div>
      <div v-if="isLeaved" class="is-leaved">
        <div class="lofty_iconfont lofty-icon-success"></div>
        <div>Thanks!I'll get back to you shortly.</div>
      </div>
      <div v-else>
        <textarea v-model="question" class="message-textarea" :style="{height: sold ? '70px': '40px'}" @focus="focus"></textarea>
        <div class="get-touch-submit-btn" :class="{disabled: !question}" @click="leaveMessage">Submit</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Tooltip from "@/admin/ui/tooltip.vue";
import SwiperCalendar from "./components/swiperCalendar.vue";
import SchedulePop from "./components/schedulePop.vue";
import MessagePop from './components/messagePop.vue'
import store from "./store.js";
import http from '@/api'
import util, { isMobile } from "@/util/index.js";
import checkLogin from "@/common/sign-log/index.js";
import dateFormat from '@/common/format/date-format.js';
const { id } = defineProps({ id: String });
const { tourType, listingId, sold } = store[id]

const isScheduled = ref(false);
const scheduleInfo = ref({});
function formatDate(timestamp = Date.now()) {
  const formatter = new Intl.DateTimeFormat('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric'
  });
  return formatter.format(new Date(timestamp));
}

const timeZone = util.getTimeZone()
function openSchedulePop(again = false) {
  if(again) {
    isScheduled.value = false
  }
  checkLogin(() => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    createApp(SchedulePop, {
      id,
      animation: isMobile ? 'bottomToUp': 'fadeIn',
      formatDate,
      isScheduled: isScheduled.value,
      onSubmit: async (params) => {
        scheduleInfo.value = params
        const data = {
          listingId,
          timeZone,
          appointmentStartTime: params.startTime,
          appointmentEndTime: params.endTime,
          recordFlag: tourType.value
        }
        const res = await http.post('/lead/operate/visitorInfo', { data })
        if(res.status.code === 0) {
          isScheduled.value = true;
        } else {
          util.toast(res.status.message, 3000)
        }
      }
    }).mount(div)
  })
}
function openMessagePop() {
  checkLogin(() => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    createApp(MessagePop, {
      animation: 'bottomToUp',
      message: question.value,
      onSubmit: (msg) => {
        question.value = msg;
        leaveMessage()
      }
    }).mount(div)
  })
}
function focus(e) {
  e.target.style.height = '200px'
}
const question = ref(sold ? 'I like this property. Do you have any recommendations for similar ones?' : 'I\'m interested in this listing')
const isLeaved = ref(false);
function leaveMessage() {
  if(!question.value) return;
  checkLogin(async() => {
    const data = {
      question: question.value,
      listingId,
      isSold: sold
    }
    const res = await http.post('/lead/operate/leaveMsg', { data })
    if(res.status.code === 0) {
      isLeaved.value = true
    } else {
      util.toast(res.status.message, 3000)
    }
  })
}

const position = ref('static')
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      position.value = 'static'
    } else if (entry.boundingClientRect.top < 0) {
        position.value = 'sticky'
      }
  });
});

onMounted(()=>{
  if(!isMobile) {
    observer.observe(document.querySelector('.lofty-detail-address'))
  }
})

onBeforeUnmount(()=>{
  if(!isMobile) {
    observer.unobserve(document.querySelector('.lofty-detail-address'));
  }
})

</script>
<style lang="scss">
.lofty-right-panel {
  top: 40px;
  right: 5%;
  transition: all 0.5s ease-in-out;
}
.is-scheduled {
  margin-top: 40px;
}
.lofty-request-tour {
  margin-top: 40px;
  height: 330px;
}

.lofty-request-tour-mobile {
  display: flex;
  align-items: center;
  padding: 0 10px;
  gap: 10px;
  > div {
    width: 160px;
    flex-grow: 1;
    margin-top: unset;
    font-size: 16px;
  }
}
.lofty-icon-help {
  color: #A8A8A8;
  margin-left: 10px;
  cursor: pointer;
  &:hover {
    color: #505050;
  }
}
.help-tip {
  font-size: 12px;
  font-family: var(--lofty-font-regular);
}
.lofty-right-container {
  border: rgba(218, 218, 218, 0.5) solid 1px;
  padding: 30px 20px;
  width: 350px;
  background: #fff;
  .title {
    text-align: center;
    font-size: 20px;
    color: rgba(25, 25, 25, 1);
    font-family: var(--lofty-font-bold);
  }
}
</style>
<style lang="scss">
.lofty-request-tour {
  .lofty-tooltip {
    left: -200px !important;
  }
}
.is-scheduled {
  text-align: center;
  color: rgba(17, 17, 17, 1);
  .scheduled-desc {
    font-size: 14px;
    font-family: var(--lofty-font-regular);
    color: rgba(80, 80, 80, 1);
    margin-top: 10px;
  }
  .scheduled-date {
    font-size: 24px;
    font-family: var(--lofty-font-bold);
    margin-top: 20px;
  }
  .scheduled-time {
    font-size: 24px;
    font-family: var(--lofty-font-bold);
    margin-top: 10px;
  }
}
.get-touch {
  margin-top: 20px;
  .message-textarea {
    width: 100%;
    resize: none;
    outline: none;
    margin: 20px 0;
    border: solid 1px #DADADA;
    line-height: normal;
    padding: 10px;
    font-family: var(--lofty-font-regular);
    &:focus {
      border-color: rgba(17, 17, 17, 1);
    }
  }
}
.is-leaved {
  text-align: center;
  .lofty-icon-success {
    margin: 20px 0;
    font-size: 40px;
    color: rgba(32, 196, 114, 1);
  }
}
.lofty-tour-type-tab {
  display: flex;
  width: 100%;
  margin-top: 30px;
  .tab-type {
    width: 50%;
    border: rgba(218, 218, 218, 0.5) 1px solid;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    height: 32px;
    font-family: var(--lofty-font-regular);
    color: rgba(80, 80, 80, 1);
  }
  .active {
    color: rgba(25, 25, 25, 1);
    border-color: rgba(17, 17, 17, 1);
    font-weight: 600;
    background: rgba(17, 17, 17, 0.05);
  }
}
.lofty-swiper-calendar {
  margin-top: 20px;
}
.schedule-tour-lofty {
  margin-top: 30px;
  font-family: var(--lofty-font-bold);
  font-size: 16px;
}
.get-touch-submit-btn {
  border: solid 1px rgba(17, 17, 17, 1);
  height: 40px;
  width: 100%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: var(--lofty-font-bold);
  font-size: 16px;
  &:hover {
    background: rgba(17, 17, 17, 0.051);
  }
  &.disabled {
    cursor: not-allowed;
  }
}
</style>