<template>
  <Form
    @submit="onSubmit"
    @invalidSubmit="onInvalidSubmit"
    v-slot="{ meta }"
  >
    <div class="page-container-grouped-styles overflow-auto">
      <siteHeader
        cmsWidgetName="SiteHeaderWidget"
      />
      <div class="fade-on-route-transition sub-container make-tall px-5">
        <textBlock
            cmsWidgetName="verifyingCoverageStatement"
            typeStyle="h5"
            justifyText="center"
            class="mt-4 mb-4"
        />
        <div
            v-html="continueWithSchedulingBodyText"
            class="mt-0" 
        />
        <textBlock
            cmsWidgetName="whatHappensNextCopy"
            class="mt-4 mb-2 fw-bold"
        />
        <div v-if="unverifiedADASNextSteps"> 
          <ol>
            <li v-for="listItem in this.arrayOfListItemsFromBodyText" :key="listItem">
              <!-- no textLink -->
              <span 
                v-if="!doesCopyContainTextLink(listItem)"
                v-html="listItem"></span>
              <!-- with textLink-->
              <template
                v-else
                v-for="copy in splitCopyOnCMSPlaceHolder(listItem)"
                :key="copy">
                <span v-if="!doesCopyContainTextLink(copy)" v-html="copy"></span>
                <span v-else>
                  <textLink
                      linkType="text"
                      :text="getRouterLinkDisplayTextFromCopy(copy)"
                      href="#!"
                      data-bs-toggle="modal"
                      data-bs-target="#RecalModal"
                      aria-label="Modal window" />
                </span>
              </template>
            </li>
          </ol>
        </div>
        <div
          v-if="unverifiedNonADASNextSteps"
          v-html="unverifiedNonADASNextStepsBodyText" >
        </div>
        <div
          v-if="unverifiedNonADASRepair"  
          v-html="unverifiedNonADASRepairBodyText" >
        </div>
        <recalModal cmsWidgetName="RecalModal" />
        <siteFooter
          cmsWidgetName="SiteFooterWidget"
          :isForwardActionDisabled="!meta.valid"
          @backClicked="backButtonAction"
          @forwardClicked="forwardButtonAction"
          ref="siteFooter"
        />
      </div>
    </div>
  </Form>
</template>
<script>

// Import Component
import baseFormMixin from '@/mixins/base-form-mixin';
import { Form } from 'vee-validate';
import siteFooter from '@/iss-components/site-footer/site-footer.vue';
import siteHeader from '@/iss-components/site-header/site-header.vue';
import siteSubHeader from '@/iss-components/site-sub-header/site-sub-header.vue';
import vehicleBanner from '@/iss-components/vehicle-banner/vehicle-banner.vue';
import textBlock from "@/digital-components/text-block/text-block";
import modal from "@/digital-components/modal/modal";
import textLink from '@/ux-components/text-link/text-link.vue';
import recalModal from '@/layouts/coverage-statement/recal-modal/recal-modal.vue';

// Import Supporting Files
import { 
  fetchCmsContentForPage,
  doesCopyContainTextLink,
  splitCopyOnCMSPlaceHolder,
  getRouterLinkDisplayTextFromCopy,
  getRouterLinkRouteFromCopy
} from '@/helpers/cms-content-helper';
import { settleAllPromises } from '@/helpers/layout-helper';
import { getDamageString } from '@/helpers/damage-helper.js';
import { useMainStore } from "@/store";

export default {
  name: 'coverage-statement',
  mixins: [baseFormMixin],
  components: {
    siteFooter,
    siteHeader,
    siteSubHeader,
    Form,
    vehicleBanner,
    textBlock,
    modal,
    textLink,
    recalModal
  },
  data() {
    return {
      isRepair: useMainStore().order.damage.isRepair,
      unverifiedADASNextSteps: false,
      unverifiedNonADASNextSteps: false,
      unverifiedNonADASRepair: false,
    };
  },
  created() {
    // check if repair or replace, if repair, display NonADASRepair
    if (this.isRepair) {
      this.unverifiedNonADASRepair = true;
    }
    else {
      this.displayReplaceCoverageStatement();
    }
  },
  computed: {
    continueWithSchedulingBodyText() {
      return this.getCmsContent('continueWithSchedulingCopy', 'BodyText');
    },
    unverifiedADASNextStepsBodyText() {
      return this.getCmsContent('UnverifiedADASNextStepsWidget', 'BodyText').replaceAll("{custom:damage}", this.damageText);
    },
    unverifiedNonADASNextStepsBodyText() {
      return this.getCmsContent('UnverifiedNonADASNextStepsWidget', 'BodyText').replaceAll("{custom:damage}", this.damageText);
    },
    unverifiedNonADASRepairBodyText() {
      return this.getCmsContent('UnverifiedNonADASRepairWidget', 'BodyText');
    },
    splitADASCoverageStatementCopy() {
      // Splits content when brackets are found in text so that text can be looped through and text-link can be injected when needed
      return this.splitCopyOnCMSPlaceHolder(this.unverifiedADASNextStepsBodyText);
    },
    arrayOfListItemsFromBodyText() {
      return this.getArrayOfListItemsFromRawCmsCopy(this.unverifiedADASNextStepsBodyText);
    },
    damageText() {
    var damageString = getDamageString();
    return damageString == "match" ? "" : damageString;
    },
  },
  async beforeRouteEnter(to, from, next) {
    // Call APIs
    const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

    // Settle promises and get results
    const promiseResultMap = [
      {
        resultKey: 'cmsContent',
        promise: cmsContentPromise,
      },
    ];

    const resultMap = await settleAllPromises(promiseResultMap);

    next((vm) => {
      vm.setCmsContent(resultMap.cmsContent);
    });
  },
  methods: {
    doesCopyContainTextLink,
    splitCopyOnCMSPlaceHolder,
    getRouterLinkDisplayTextFromCopy,
    getRouterLinkRouteFromCopy,
    arePagePrerequisiteValid() {
      return true;
    },
    backButtonAction() {
      /**
       * this.navigationScenarios comes from base-mixin
       */
      this.$router.navigate(this.navigationScenarios.CLICKED_BACK, this.$route);
    },
    displayReplaceCoverageStatement() {
      // get array of parts for vehicle
      let parts = useMainStore().order.lineItems.glassParts;
  
      // if ADAS, display ADASNextSteps
      if (parts.filter(part => part.requiresRecalibration).length > 0) {
        this.unverifiedADASNextSteps = true;
      }
      // if non-ADAS, display NonADASNextSteps
      else {
        this.unverifiedNonADASNextSteps = true;
      }
    },
    stripOlTagFromCopy(copy) {
      const regex = /(?:<ol(?:.*?)>)|(?:<\/ol>)/g;
      return copy.replace(regex, "");
    },
    getArrayOfListItemsFromRawCmsCopy(copy) {
      const withoutOlTags = this.stripOlTagFromCopy(copy);
      return withoutOlTags
          .split(/(?:<li(?:.*?)>)|(?:<\/li>)/g)
          .filter((lineItem) => lineItem);
    },
  },
    async forwardButtonAction() {},
    resetDependentState() {},
};
</script>

<style lang="scss">
    ol {
        margin-left: -1rem;
        li {
            margin-bottom: .5rem;
        }
    }
</style>
