<template>
    <div class="save-progress-popup-question" :class="[isProgressSaved ? 'progress-saved' : '']">
        <modal
            :ref="modalName"
            :headerText="modalHeaderText"
            suppressPageScroll
            :onModalClosedCallback="onModalClosed"
            :footerButtonText="modalButtonText"
            :isFooterButtonPrimary="true"
            :isFooterButtonSuppressed="isPhoneTabSelected && !isProgressSaved"
            @footer-button-event="saveProgress">
            <p class="modal-body-inner">{{ modalBodyText }}</p>
            <fieldset class="save-progress-popup-question__tabs">
                <div class="save-progress-popup-question__tab-list" role="radiogroup">
                    <label
                        v-for="tab in contactTabs"
                        :key="tab.value"
                        class="save-progress-popup-question__tab"
                        :class="{
                            'save-progress-popup-question__tab--active':
                                contactMethod === tab.value,
                            'save-progress-popup-question__tab--disabled':
                                isContactMethodTabDisabled(tab.value),
                        }">
                        <input
                            type="radio"
                            class="save-progress-popup-question__tab-input"
                            name="saveProgressPopupContactMethod"
                            :value="tab.value"
                            :checked="contactMethod === tab.value"
                            :disabled="isContactMethodTabDisabled(tab.value)"
                            @change="selectContactMethod(tab.value)" />
                        <span class="save-progress-popup-question__tab-label">{{ tab.label }}</span>
                    </label>
                </div>
            </fieldset>
            <div v-if="isPhoneTabSelected" class="save-progress-popup-question__phone-fields">
                <phoneNumberQuestion
                    v-model="userInput"
                    :cmsWidgetName="phoneQuestionWidgetName"
                    placeholderText=""
                    :isDisabled="isProgressSaved"
                    isRequired
                    validationRules="phone-number-required" />
                <saveProgressPopupSmsConsentQuestion
                    ref="smsConsentQuestion"
                    v-model="smsConsent"
                    :consentCopy="smsConsentCopy"
                    :isDisabled="isProgressSaved"
                    :showConsentErrors="showConsentErrors"
                    :showConsentManagement="showConsentManagement" />
            </div>
            <saveProgressQuestion
                v-else
                ref="saveProgressQuestion"
                v-model="userInput"
                :cmsWidgetName="emailQuestionWidgetName"
                :isDisabled="isProgressSaved"
                class="save-progress-popup-question" />
            <template v-slot:modal-footer-slot>
                <buttonMain
                    ref="skipButton"
                    type="button"
                    :buttonText="buttonText"
                    loaderColor="white"
                    :suppressLoader="true"
                    class="skip-button"
                    @click-event="closeModal" />
                <modalButtonMain
                    v-if="isPhoneTabSelected && !isProgressSaved"
                    ref="phoneSendButton"
                    :isPrimary="true"
                    class="w-100 modal-footer-button"
                    :buttonText="modalButtonText"
                    @click-event="validatePhoneAndSave" />
                <p class="modal-disclaimer" v-html="modalDisclaimerText"></p>
            </template>
            <alert
                class="my-4"
                v-if="isProgressSaved"
                cmsWidgetName="SaveProgressModalAlertWidget"
                alertClass="alert-success" />
        </modal>
    </div>
</template>

<script>
import saveProgressQuestion from "@/fmg-components/save-progress-modal-question/save-progress-question/save-progress-question";
import saveProgressPopupSmsConsentQuestion from "./save-progress-popup-sms-consent-question";
import phoneNumberQuestion from "@/digital-components/phone-number-question/phone-number-question";
import modal from "@/digital-components/modal/modal";
import modalButtonMain from "@/digital-components/modal/ux-components/modal-button-main/modal-button-main";
import buttonMain from "@/ux-components/button-main/button-main";
import alert from "@/ux-components/alert/alert";
import { saveQuote } from "@/helpers/heritage-integration/order-helper.js";
import {
    saveProgressPopupContactToStore,
    saveProgressPopupContactMethods,
} from "@/helpers/save-progress-popup-contact-helper";
import {
    defaultSaveProgressSmsConsent,
    getSaveProgressSmsConsentFallbackCopy,
    getSaveProgressSmsConsentConfig,
    hasSaveProgressSmsConsentSelection,
} from "@/helpers/save-progress-sms-consent/save-progress-sms-consent-helper";
import { defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";

const PHONE_SPECIFIC_WIDGET = "SaveProgressPopupWidget_PhoneSpecific";
const EMAIL_SPECIFIC_WIDGET = "SaveProgressPopupWidget_EmailSpecific";
const PHONE_QUESTION_WIDGET = "SaveProgressPopupPhoneQuestionWidget";
const EMAIL_QUESTION_WIDGET = "SaveProgressPopupEmailQuestionWidget";

defineRule("phone-number-required", required(errorMessages.PHONE_REQUIRED));

export default {
    name: "save-progress-popup-question",

    data() {
        return {
            userInput: "",
            contactMethod: saveProgressPopupContactMethods.EMAIL,
            smsConsent: defaultSaveProgressSmsConsent(),
            smsConsentCopy: getSaveProgressSmsConsentFallbackCopy(),
            isProgressSaved: false,
            savedContactMethod: null,
            showConsentErrors: false,
        };
    },
    watch: {
        smsConsent: {
            handler(consent) {
                if (hasSaveProgressSmsConsentSelection(consent, this.showConsentManagement)) {
                    this.showConsentErrors = false;
                }
            },
            deep: true,
        },
    },
    async mounted() {
        this.loadSmsConsentConfig();

        if (this.showSaveProgressPopup) this.modal.openModal();
    },
    emits: ["close-save-progress-popup", "save-progress-saved"],
    props: {
        modalWidgetName: String,
        pageName: String,
        showSaveProgressPopup: Boolean,
        showConsentManagement: Boolean,
    },
    computed: {
        buttonText() {
            return this.isProgressSaved
                ? "Close"
                : this.getCmsContent(this.modalWidgetName, "BodyText2");
        },
        modalHeaderText() {
            return this.getCmsContent(this.modalWidgetName, "HeaderText");
        },
        modalBodyText() {
            return this.getCmsContent(this.modalWidgetName, "BodyText");
        },
        modalButtonText() {
            return this.getCmsContent(this.modalWidgetName, "FooterText");
        },
        modalDisclaimerText() {
            const disclaimerWidgetName = this.isPhoneTabSelected
                ? PHONE_SPECIFIC_WIDGET
                : EMAIL_SPECIFIC_WIDGET;

            return this.getCmsContent(disclaimerWidgetName, "BodyText");
        },
        modalName() {
            return this.modalWidgetName;
        },
        modal() {
            return this.$refs[this.modalName];
        },
        contactTabs() {
            return [
                {
                    label: this.getCmsContent(PHONE_SPECIFIC_WIDGET, "HeadlineText") || "Phone",
                    value: saveProgressPopupContactMethods.PHONE,
                },
                {
                    label: this.getCmsContent(EMAIL_SPECIFIC_WIDGET, "HeadlineText") || "Email",
                    value: saveProgressPopupContactMethods.EMAIL,
                },
            ];
        },
        isPhoneTabSelected() {
            return this.contactMethod === saveProgressPopupContactMethods.PHONE;
        },
        phoneQuestionWidgetName() {
            return PHONE_QUESTION_WIDGET;
        },
        emailQuestionWidgetName() {
            return EMAIL_QUESTION_WIDGET;
        },
    },
    methods: {
        loadSmsConsentConfig() {
            const config = getSaveProgressSmsConsentConfig();
            this.smsConsentCopy = config.copy;

            if (!this.isProgressSaved) {
                this.smsConsent = config.value;
            }
        },
        selectContactMethod(contactMethod) {
            if (this.isProgressSaved || this.contactMethod === contactMethod) {
                return;
            }

            this.contactMethod = contactMethod;
            this.userInput = "";
            this.smsConsent = defaultSaveProgressSmsConsent();
            this.showConsentErrors = false;
        },
        isContactMethodTabDisabled(contactMethod) {
            return this.isProgressSaved && contactMethod !== this.savedContactMethod;
        },
        closeModal() {
            this.modal.closeModal();
        },
        onModalClosed() {
            this.showConsentErrors = false;
            this.$emit("close-save-progress-popup");
        },
        async validatePhoneAndSave() {
            try {
                const validationResult = await this.modal.validate();

                if (!validationResult.valid) {
                    return;
                }

                if (
                    !hasSaveProgressSmsConsentSelection(this.smsConsent, this.showConsentManagement)
                ) {
                    this.showConsentErrors = true;
                    await this.scrollConsentIntoView();
                    return;
                }

                this.showConsentErrors = false;
                await this.saveProgress();
            } finally {
                this.resetPhoneSendButtonStyle();
            }
        },
        resetPhoneSendButtonStyle() {
            this.$refs.phoneSendButton?.resetButtonStyle();
        },
        async scrollConsentIntoView() {
            await this.$nextTick();
            const consentEl =
                this.$refs.smsConsentQuestion?.$el ??
                this.$el?.querySelector(".save-progress-popup-sms-consent");

            consentEl?.scrollIntoView({ behavior: "smooth", block: "nearest" });
        },
        async saveProgress() {
            await saveProgressPopupContactToStore(this.dispatchStoreAction, {
                contactMethod: this.contactMethod,
                userInput: this.userInput,
                smsConsent: this.smsConsent,
            });

            // send store call to send to new API (that triggers an email/SMS send)
            await saveQuote({ pageNameToLog: this.pageName });

            // hide save progress button; show success message alert
            this.savedContactMethod = this.contactMethod;
            this.isProgressSaved = true;

            // communicate to parent the new status
            this.$emit("save-progress-saved");
        },
    },

    components: {
        modal,
        modalButtonMain,
        buttonMain,
        saveProgressQuestion,
        phoneNumberQuestion,
        saveProgressPopupSmsConsentQuestion,
        alert,
    },
};
</script>

<style lang="scss">
.save-progress-popup-question {
    order: 2;
    margin-bottom: 1.5rem;

    .modal-header {
        padding-top: 1rem;

        .modal-title {
            padding-top: 4.25rem;
        }

        .modal-title::before {
            position: absolute;
            content: "";
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 63 62'%3E%3Cpath fill='%23B3B4B5' d='M31.5 62c17.052 0 30.876-1.503 30.876-3.358 0-1.854-13.824-3.358-30.876-3.358S.624 56.788.624 58.642C.624 60.497 14.448 62 31.5 62Z' opacity='.4'/%3E%3Cpath fill='%23DA291C' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m33.358 52.715-4.574 4.573-24.192-24.2 4.491-4.491 24.275 24.118Z'/%3E%3Cpath fill='%23fff' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M58.408 13.402 55.61 30.469 33.356 52.715 9.083 28.597 31.411 6.269l17.067-2.797 9.93 9.93Z'/%3E%3Cpath fill='%23fff' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M45.586 19.907a3.618 3.618 0 1 0 0-7.237 3.618 3.618 0 0 0 0 7.237Z'/%3E%3C/svg%3E");
            width: 3.875rem;
            height: 3.875rem;
            top: 2.5rem;
            left: calc(50% - 3.875rem / 2);
        }
    }

    .btn.btn-secondary.skip-button {
        order: 4;
        position: relative;
        color: $black;
        border: none;
        border-radius: 0.25rem;
        font-weight: 900;
        font-size: 0.875rem;
        text-align: center;
        display: inline-block;
        width: auto;
        height: auto;
        text-decoration: underline;
        text-underline-offset: 0.25rem;
        line-height: 1rem;
        padding: 0 0 4px 0;
        margin: 0 auto 1.5rem auto;
        transition: all 150ms linear;
        background: none;
        @include media-breakpoint-up(md) {
            font-size: 1rem;
        }

        &:hover,
        &:active,
        &:focus {
            color: $blue-700;
            background: none;
            box-shadow: none;
        }
        &:focus-visible {
            outline: none;
            box-shadow:
                0 0 0 3px $white,
                0 0 0 5.5px $blue-300;
        }

        &.delay {
            // fixes flicker while transitioning between states
            transition: background 0s 0s ease-in-out;
        }
    }
    .alert {
        border-radius: $border-radius-lg;
        border: 1px solid $green;
        order: 2;
        margin: 0 0 1.5rem 0;
    }
    .alert-heading {
        position: relative;
        font-weight: 600;
        font-size: 1rem;
        color: $black;
        text-align: left;
        padding-left: 1.5rem;
        &::before {
            position: absolute;
            content: "";
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='%230C7E47' d='M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0Zm3.7 6.171-4.449 4.45a.559.559 0 0 1-.8 0l-2.16-2.16a.563.563 0 0 1 .792-.8l1.76 1.76 4.066-4.042a.563.563 0 1 1 .792.8v-.008Z'/%3E%3C/svg%3E");
            width: 1rem;
            height: 1rem;
            top: 6px;
            left: 0;
        }
    }
    .modal.modal-component .modal-dialog .modal-content {
        max-height: calc(100dvh - 1rem);
        display: flex;
        flex-direction: column;
        overflow: hidden;

        p.modal-body {
            padding: 0;
        }
        .modal-body {
            display: flex;
            flex-direction: column;
            padding: 0 1.5rem;
            overflow-y: auto;
            flex: 1 1 auto;
            min-height: 0;

            .textbox-question {
                padding: 0;
                margin: 0 0 1.5rem 0;

                label {
                    text-align: left;
                    font-weight: 900;
                }
            }
        }
        .modal-body-inner {
            text-align: center;
            margin-bottom: 0.5rem;
        }

        .save-progress-popup-question__tabs {
            border: 0;
            margin: 0 0 1rem 0;
            padding: 0;
        }

        .save-progress-popup-question__tab-list {
            display: flex;
            width: 100%;
        }

        .save-progress-popup-question__tab {
            flex: 1 1 50%;
            display: grid;
            min-height: 3.25rem;
            margin: 0;
            cursor: pointer;
        }

        .save-progress-popup-question__tab-input {
            grid-area: 1 / 1;
            width: 100%;
            height: 100%;
            margin: 0;
            opacity: 0;
            cursor: inherit;

            &:focus-visible + .save-progress-popup-question__tab-label {
                outline: 2px solid $blue;
                outline-offset: 2px;
                border-radius: 0.25rem;
            }
        }

        .save-progress-popup-question__tab-label {
            grid-area: 1 / 1;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 0.875rem 0.5rem;
            text-align: center;
            text-transform: uppercase;
            font-size: 0.875rem;
            font-weight: 600;
            line-height: 1.25rem;
            color: $gray-600;
            border-bottom: 3px solid transparent;
            transition:
                color 150ms linear,
                border-color 150ms linear;
        }

        .save-progress-popup-question__tab--active .save-progress-popup-question__tab-label {
            color: $red;
            border-bottom-color: $red;
        }

        .save-progress-popup-question__tab--disabled {
            cursor: not-allowed;

            .save-progress-popup-question__tab-label {
                color: $gray-400;
            }
        }

        .save-progress-popup-question__phone-fields {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            margin: 0 0 1.5rem 0;
        }

        .phone-number-question {
            margin: 0;

            label {
                text-align: left;
                font-weight: 900;
            }
        }

        .modal-footer {
            padding: 0 1.5rem;
            margin: 0 0 1.5rem 0;

            button.btn {
                order: 1;
                margin-bottom: 1.5rem;
            }
            button.btn.skip-button {
                padding: 0;
                order: 2;
                font-size: 0.875rem;
                @include media-breakpoint-up(md) {
                    font-size: 1rem;
                }
            }
            .modal-disclaimer {
                font-size: 0.8125rem;
                color: #525656;
                text-align: left;
                order: 3;
                margin: 0;
                max-height: calc(100dvh - 30rem);
                overflow-y: auto;

                a {
                    text-decoration: none;
                }
            }
        }
    }

    &.progress-saved {
        .modal-footer-button,
        .modal-disclaimer {
            display: none;
        }
        .skip-button {
            margin-bottom: 0;
        }
    }
}
</style>
