<template>
    <div class="cart">
        <div class="px-0" v-if="isCartReadyToLoad">
            <div
                class="row vin-toggle flex align-items-center pt-4"
                :class="[
                    isCollapsible ? (isExpanded ? 'expanded' : '') : 'expanded non-collapsible',
                ]"
                @click="toggleIsExpanded()">
                <a
                    aria-label="expand cart"
                    href="javascript:void(0)"
                    class="col d-flex justify-content-between py-0">
                    <span class="label">{{ cartHeaderText }}</span>
                    <span class="label amount-due larger">
                        {{ getLineItemAmount(amountDue, showCoverageAsPending) }}
                    </span>
                </a>
            </div>
            <div class="cart-panel">
                <div class="price-table">
                    <!-- Deductible, if applicable -->
                    <div v-if="deductibleLineItem" class="deductible">
                        <textBlock cmsWidgetName="DeductibleTextWidget" />
                        <span>
                            {{
                                getLineItemAmount(
                                    deductibleLineItem.subTotal,
                                    showCoverageAsPending
                                )
                            }}
                        </span>
                    </div>

                    <!-- Service Type -->
                    <div class="service-type">
                        <textBlock :cmsWidgetName="servicePackageTitleWidget" />
                        <span>
                            {{ getLineItemAmount(packagePrice) }}
                        </span>
                        <span
                            v-if="packagePriceWithoutDiscount > packagePrice"
                            class="struck-out-price">
                            {{ getLineItemAmount(packagePriceWithoutDiscount) }}
                        </span>
                    </div>

                    <!-- Packaged Cart Items -->
                    <div
                        v-for="(cartItem, i) in packageCartItems"
                        :key="i"
                        class="packaged-cart-item">
                        <span>
                            <span :class="cartItem.category === 'promos' ? 'promo' : ''">
                                {{ cartItem.name }}
                            </span>
                        </span>
                        <textLink
                            v-if="allowItemRemoval"
                            ref="removeLink"
                            linkType="text"
                            :text="removeLinkText"
                            href="javascript:void(0)"
                            @click-event="removeItem(cartItem.cartItemType, cartItem.category)">
                            <template v-slot:after-text>
                                <span class="sr-only">{{ cartItem.name }}</span>
                            </template>
                        </textLink>
                    </div>

                    <!-- Nonpackaged Cart Items -->
                    <div
                        v-for="(cartItem, i) in nonpackageCartItems"
                        :key="i"
                        class="non-packaged-cart-item"
                        :class="[
                            i % 2 == 0 ? 'even' : 'odd',
                            cartItem.isRemovable ? 'removable-cart-item' : '',
                        ]">
                        <span v-if="!this.shouldShowInfoIcon(cartItem)">{{ cartItem.name }}</span>
                        <textLink
                            v-if="allowItemRemoval && cartItem.isRemovable"
                            ref="removeLink"
                            linkType="text"
                            :text="removeLinkText"
                            href="javascript:void(0)"
                            @click-event="removeItem(cartItem.cartItemType, cartItem.category)" />
                        <span v-else-if="cartItem == recycleFeeCartItem">
                            {{ recycleFeeCartItem.name }}
                            <toolTip
                                :cmsWidgetName="recyclingModalCmsWidgetName"
                                :customBodyText="recyclingToolTipBodyText" />
                        </span>
                        <span v-if="cartItem == msrFeeCartItem">
                            {{ msrFeeCartItem.name }}
                            <toolTip
                                :cmsWidgetName="msrModalCmsWidgetName"
                                :customBodyText="msrToolTipBodyText" />
                        </span>
                        <span
                            v-if="
                                !showCoverageAsVerified ||
                                cartItem.name === 'Recycling' ||
                                (showCoverageAsVerified && !cartItem.isCoveredByInsurance)
                            ">
                            {{ getLineItemAmount(cartItem.subTotal, null, cartItem.category) }}
                        </span>
                    </div>

                    <!-- Sub total, sales tax, total columns -->
                    <div class="sub-total">
                        <span>{{ subtotalText }}</span>
                        <span>{{ getLineItemAmount(subTotal, showCoverageAsPending) }}</span>
                    </div>
                    <div class="sales-tax" v-show="showSalesTax">
                        <span>{{ salesTaxText }}</span>
                        <span>{{ getLineItemAmount(salesTax) }}</span>
                    </div>
                    <div v-if="showAsPaid" class="amount-paid">
                        <span>{{ amountPaidText }}</span>
                        <span>{{ getLineItemAmount(amountPaid) }}</span>
                    </div>
                    <div v-if="donationCartItem" class="donation-amount">
                        <span>{{ donationCartItemName }}</span>
                        <span>{{ getLineItemAmount(donationCartItem.sellingPrice) }}</span>
                    </div>
                    <div class="amount-due">
                        <span>{{ amountDueText }}</span>
                        <span>{{ getLineItemAmount(amountDue, showCoverageAsPending) }}</span>
                    </div>
                </div>
                <div
                    v-if="insuranceCompanyName && (showCoverageAsVerified || showCoverageAsPending)"
                    class="insurance-company-name caption">
                    {{ insuranceCompanyName }}
                </div>
                <promoModalQuestion
                    ref="promoModalQuestion"
                    class="small mt-4"
                    v-model="lineItems"
                    :addableVaps="availableVaps"
                    :pageName="pageName"
                    modalWidgetName="PromoModalWidget"
                    @promoAdded="saveVaps" />
                <removeMsrFeeModal
                    modalWidgetName="RemoveMsrFeeModalWidget"
                    ref="removeMsrFeeModal"
                    @switchToInshop="switchToInshop" />
            </div>
        </div>
        <div
            class="my-2 lh-1 applied-promo-tag"
            v-for="(promoCode, i) in getPromoCodeList"
            :key="i">
            <span class="caption">
                Promo code
                <span class="promo-code">{{ promoCode }}</span>
                applied
            </span>
        </div>
    </div>
</template>

<script>
// Components
import textLink from "@/ux-components/text-link/text-link";
import textBlock from "@/digital-components/text-block/text-block";
import promoModalQuestion from "@/fmg-components/promo-modal-question/promo-modal-question";
import removeMsrFeeModal from "./remove-msr-fee-modal/remove-msr-fee-modal.vue";
import toolTip from "@/ux-components/tool-tip/tool-tip.vue";

// Mixins
import baseMixin from "@/mixins/base-mixin.js";
import experimentMixin from "@/mixins/experiment-mixin.js";

// Helpers
import { deepClone } from "@/helpers/object-helper";
import {
    getHighestFullySatisfiedTier,
    getPackageContents,
    getDiscountedPackageName,
} from "@/helpers/service-package-helper";
import { getPromoCodeWithoutBundleIdentifier } from "@/helpers/promotions-helper";
import { storeActions } from "@/constants/store-actions";
import {
    getDisplayAmountDue,
    getAmountDue,
    getSubTotal,
    getSalesTax,
    getAmountDueWithDonation,
} from "@/helpers/pricing-helper.js";
import { formatToUSDollar } from "@/helpers/cms-content-helper";

// Constants
import { partTypeStrings } from "@/constants/part-type-strings";
import { cartItemCategories } from "@/constants/cart-item-categories";
import { cartItemTypes } from "@/constants/cart-item-types";
import { coverageStatus, cartItemTypesCoveredByInsurance } from "@/constants/insurance";
import { experimentSettings } from "@/constants/experiments";
import { quotePageDiscountTable } from "@/constants/quote-page-discounts";
import { partNumberStrings } from "@/constants/part-number-strings";

export default {
    name: "cart",
    props: {
        modelValue: Object,
        inactivePromos: Object,
        damage: Object,
        servicePackageOptionsCmsName: String,
        availableVaps: Object,
        pageName: String,
        allowItemRemoval: Boolean,
        recyclingModalCmsWidgetName: String,
        msrModalCmsWidgetName: String,
        showAsPaid: Boolean,
        isInsurance: Boolean,
        insuranceDeductible: Number,
        insuranceCompanyName: String,
        showInsuranceCoverageAs: String,
        shouldHideRecalibration: Boolean,
        isItac: Boolean,
        isNoComp: Boolean,
        isExpandedOnLoad: Boolean,
        isCollapsible: { type: Boolean, default: true },
        isMSRFeeApplicable: Boolean,
        IsMSRFeeCoveredByInsurance: Boolean,
        donationCartItem: Object,
    },
    data() {
        return {
            isExpanded: false,
            currencyFormatter: new Intl.NumberFormat("en-US", {
                style: "currency",
                currency: "USD",
            }),
        };
    },
    methods: {
        openModal(modalName) {
            this.$refs[modalName].openModal();
        },
        toggleIsExpanded() {
            this.isExpanded = !this.isExpanded;
        },
        updateIsExpandedWithDefault() {
            this.isExpanded = this.isExpandedOnLoad;
        },
        getVapsPrice(packageName) {
            const vapsItems = this.getVapsCartItemsForSelectedPackage(packageName);

            let subTotal = 0;

            vapsItems.forEach((item) => {
                subTotal += item.subTotal;
            });

            return subTotal;
        },
        getPromoDiscounts() {
            const promoItems = this.promoCartItems;

            let subTotal = 0;

            promoItems?.forEach((item) => {
                subTotal += item.subTotal;
            });

            return subTotal;
        },
        getQuotePageDiscount() {
            const quotePageDiscountLineItems = this.quotePageDiscountCartItem;
            let subTotal = 0;

            subTotal += quotePageDiscountLineItems?.subTotal ?? 0;
            return subTotal;
        },
        getVapsCartItemsForSelectedPackage(packageName) {
            const packageContentTypes = getPackageContents(
                this.glassToReplace,
                this.availableLineItems,
                this.isRepair,
                packageName
            );

            let vapsCartItemsForSelectedPackage = [];

            this.cartItems.forEach((cartItem) => {
                packageContentTypes.forEach((vapType) => {
                    if (cartItem.cartItemType.includes(vapType)) {
                        vapsCartItemsForSelectedPackage.push(cartItem);
                    }
                });
            });

            if (this.promoCartItems) {
                this.promoCartItems.forEach((promoCartItem) => {
                    vapsCartItemsForSelectedPackage.push(promoCartItem);
                });
            }

            return vapsCartItemsForSelectedPackage;
        },
        getCmsContentForVapsType(vapsType) {
            const vapsItemDescriptions = this.getCmsContent("VapsItemDescriptions", "Answers");

            if (!vapsItemDescriptions) {
                return "";
            }

            const vapsTypeName = vapsItemDescriptions.find((entry) => entry.Name === vapsType);

            return vapsTypeName.Text;
        },

        getLineItemAmount(amount, useVerifyingText, category) {
            if (useVerifyingText) return this.verifyingCoverageText;
            return category == cartItemCategories.PROMOS ||
                category == cartItemCategories.QUOTE_PAGE_DISCOUNT
                ? "(" + this.currencyFormatter.format(amount * -1) + ")"
                : this.currencyFormatter.format(amount);
        },

        async removeItem(cartItemType, category) {
            if (cartItemType == cartItemTypes.MOBILE_FEE && this.isMSRFeeApplicable) {
                this.$refs.removeMsrFeeModal.openModal();
                return false;
            }
            this.lineItems[category] = this.lineItems[category].filter(
                (lineItemsToKeep) => lineItemsToKeep.cartItemType != cartItemType
            );
            let shouldSaveSupportingItems = category == cartItemCategories.SUPPORTING_ITEMS;
            if (category == cartItemCategories.VAPS || category == cartItemCategories.PROMOS) {
                this.saveVaps(this.lineItems);
                // Check if service package discount should be removed after vaps change
                if (this.quotePageDiscountCartItem) {
                    const existingLineItem = this.quotePageDiscountCartItem.lineItems.at(0);
                    const discountInfo = quotePageDiscountTable.find(
                        (info) => info.partNumber === existingLineItem?.partNumber
                    );
                    const packageLevelForDiscount = discountInfo?.packageLevel;

                    if (this.packageLevel !== packageLevelForDiscount) {
                        this.lineItems.supportingItems = this.lineItems.supportingItems.filter(
                            (lineItemsToKeep) =>
                                lineItemsToKeep.cartItemType !=
                                this.quotePageDiscountCartItem.cartItemType
                        );
                        shouldSaveSupportingItems = true;
                    }
                }
            }
            if (shouldSaveSupportingItems) {
                await this.dispatchStoreAction(
                    storeActions.SAVE_SUPPORTING_ITEMS_SUPPRESSING_STATE_RESETTING,
                    this.lineItems.supportingItems,
                    false
                );
            }
            this.$emit("itemRemoved");
        },

        async saveVaps(lineItems) {
            this.lineItems.vaps = [...lineItems.vaps];
            this.lineItems.promos = [...lineItems.promos];
            await this.dispatchStoreAction(storeActions.SAVE_VAPS, this.lineItems.vaps, false);

            // any new promos that are also in inactive list?
            const newInactivePromos = this.inactivePromos.filter((promo) => {
                return this.lineItems.promos.includes(promo);
            });
            this.updateInactivePromos(newInactivePromos);

            await this.dispatchStoreAction(
                storeActions.SAVE_ACTIVE_AND_OR_INACTIVE_PROMOS,
                {
                    activePromos: this.lineItems.promos,
                    inactivePromos: this.inactivePromos,
                },
                false
            );
        },

        updateInactivePromos(newInactivePromos) {
            this.$emit("update:inactivePromos", newInactivePromos);
        },
        getPromoCodeList() {
            if (this.$refs["promoModalQuestion"]) {
                return this.$refs["promoModalQuestion"].getPromoCodeList();
            }
            return [];
        },
        shouldShowInfoIcon(cartItem) {
            return cartItem == this.recycleFeeCartItem || cartItem == this.msrFeeCartItem;
        },
        switchToInshop() {
            this.$emit("switchToInshop");
        },
    },
    computed: {
        isCartReadyToLoad() {
            this.updateIsExpandedWithDefault();
            return this.isExpandedOnLoad !== null;
        },
        lineItems: {
            get: function () {
                return this.modelValue;
            },
            set: function (newValue) {
                this.$emit("update:modelValue", newValue);
            },
        },
        lineItemsWithoutRecal() {
            if (!this.lineItems || this.lineItems.length < 1) return;

            const lineItemsCopy = deepClone(this.lineItems);
            lineItemsCopy.glassParts = lineItemsCopy.glassParts
                ? baseMixin.methods.filterOutRecalibration(lineItemsCopy?.glassParts)
                : [];
            return lineItemsCopy;
        },
        showCoverageAsPending() {
            return this.showInsuranceCoverageAs === coverageStatus.PENDING;
        },
        showCoverageAsVerified() {
            return this.showInsuranceCoverageAs === coverageStatus.VERIFIED;
        },
        showSalesTax() {
            const tax = parseFloat(this.salesTax).toFixed(2);
            return tax > 0;
        },
        currentDeductible() {
            const deductible = this.insuranceDeductible;
            if (!(deductible === 0 || deductible > 0)) {
                global.$logger.logError("Error: currentDeductible should not be null");
            }
            return deductible;
        },
        screenReaderTotalAmountDueText() {
            return this.getCmsContent("ScreenReaderTotalAmountDueWidget", "Text");
        },
        screenReaderPackagePriceText() {
            return this.getCmsContent("ScreenReaderPackagePriceTextWidget", "Text");
        },
        screenReaderRemoveVapsText() {
            return this.getCmsContent("ScreenReaderRemoveVapsWidget", "Text");
        },
        screenReaderRecycleFeeText() {
            return this.getCmsContent("ScreenReaderRecycleFeeWidget", "Text");
        },
        screenReaderSubTotalText() {
            return this.getCmsContent("ScreenReaderSubTotalWidget", "Text");
        },
        screenReaderAmountPaidText() {
            return this.getCmsContent("ScreenReaderAmountPaidWidget", "Text");
        },
        screenReaderSalesTaxText() {
            return this.getCmsContent("ScreenReaderSalesTaxWidget", "Text");
        },
        availableLineItems() {
            if (!this.lineItems || this.lineItems.length < 1) {
                return [];
            }
            let supportingItemsToAdd = [];
            if (this.lineItems.supportingItems) {
                supportingItemsToAdd = this.lineItems.supportingItems.filter(
                    (item) => item.partType !== partTypeStrings.DONATION
                );
            }
            return [
                ...(this.lineItems.glassParts ?? []),
                ...supportingItemsToAdd,
                ...(this.availableVaps ?? []),
            ];
        },
        cartItems: {
            get: function () {
                let cartItems = [];

                if (this.frontWipersCartItem) {
                    cartItems.push(this.frontWipersCartItem);
                }

                if (this.rearWipersCartItem) {
                    cartItems.push(this.rearWipersCartItem);
                }

                if (this.rainRepelCartItem) {
                    cartItems.push(this.rainRepelCartItem);
                }

                if (this.glassPartCartItems) {
                    this.glassPartCartItems.forEach((glassPartCartItem) => {
                        cartItems.push(glassPartCartItem);
                    });
                }

                if (this.otherSupportingItemsCartItem) {
                    cartItems.push(this.otherSupportingItemsCartItem);
                }

                if (this.recycleFeeCartItem) {
                    cartItems.push(this.recycleFeeCartItem);
                }

                if (this.suppliesRepairCartItem) {
                    cartItems.push(this.suppliesRepairCartItem);
                }

                if (this.mobileFeeCartItem) {
                    cartItems.push(this.mobileFeeCartItem);
                }

                if (this.msrFeeCartItem) {
                    cartItems.push(this.msrFeeCartItem);
                }

                if (this.quotePageDiscountCartItem) {
                    cartItems.push(this.quotePageDiscountCartItem);
                }

                if (this.premiumAppointmentDiscountCartItem) {
                    cartItems.push(this.premiumAppointmentDiscountCartItem);
                }

                if (this.promoCartItems) {
                    this.promoCartItems.forEach((promoCartItem) => {
                        cartItems.push(promoCartItem);
                    });
                }

                return cartItems;
            },
        },
        servicePackageTitleWidget() {
            const servicePackageNames = this.getCmsContent(
                this.servicePackageOptionsCmsName,
                "Answers"
            );

            if (!servicePackageNames) {
                return "";
            }

            const currentPackage = servicePackageNames.find(
                (entry) => entry.Name === this.packageLevel
            );

            return currentPackage.SubWidgetName;
        },
        packageLevel() {
            const tier = getHighestFullySatisfiedTier(
                this.glassToReplace,
                this.availableLineItems,
                this.isRepair,
                this.vaps
            );

            return tier;
        },
        packagePrice() {
            let packagePrice = 0;

            if (!this.isInsurance && this.shouldHideRecalibration) {
                // Update packagePrice if Cash only && is part of RemoveRecal experiment
                packagePrice = baseMixin.methods.getTierOnePackagePrice(
                    baseMixin.methods.filterOutFees(
                        baseMixin.methods.filterOutRecalibration(this.availableLineItems) // Strip out recal before filtering out fees
                    )
                );
            } else if (!this.showCoverageAsVerified && !this.showCoverageAsPending) {
                // Update packagePrice if is verified insurance OR if Cash && not part of RemoveRecal experiment
                packagePrice = baseMixin.methods.getTierOnePackagePrice(
                    baseMixin.methods.filterOutFees(this.availableLineItems)
                );
            }

            packagePrice += this.getVapsPrice(this.packageLevel);
            if (this.quotePageDiscountCartItem) {
                packagePrice -= this.getQuotePageDiscount();
            }

            return packagePrice;
        },
        packagePriceWithoutDiscount() {
            let fullPrice = this.packagePrice;
            let discount = this.getPromoDiscounts();
            fullPrice += Math.abs(discount);
            return fullPrice;
        },
        isRepair() {
            if (!this.damage) {
                return;
            }

            return this.damage.isRepair;
        },
        glassToReplace() {
            if (!this.damage) {
                return;
            }

            return this.damage.glassToReplace;
        },
        glassParts() {
            const glassParts = this.lineItems?.glassParts;
            return glassParts?.length > 0 ? glassParts : [];
        },
        vaps() {
            const vaps = this.lineItems?.vaps;
            return vaps?.length > 0 ? vaps : [];
        },
        supportingItems() {
            const supportingItems = this.lineItems?.supportingItems;
            return supportingItems?.length > 0 ? supportingItems : [];
        },
        promos() {
            const promos = this.lineItems?.promos;
            return promos?.length > 0 ? promos : [];
        },
        deductibleLineItemName() {
            return this.getCmsContent("DeductibleTextWidget", "Text");
        },
        deductibleLineItem() {
            let lineItem = null;

            if (this.showCoverageAsVerified || this.showCoverageAsPending) {
                lineItem = {
                    name: this.deductibleLineItemName,
                    subTotal: this.currentDeductible,
                };
            }

            return lineItem;
        },
        verifyingCoverageText() {
            return this.getCmsContent("VerifyingCoverageTextWidget", "Text");
        },
        // Cart Item Groupings
        packageCartItems() {
            return this.getVapsCartItemsForSelectedPackage(this.packageLevel);
        },
        nonpackageCartItems() {
            const nonpackageCartItems = [];

            this.cartItems.forEach((cartItem) => {
                if (!this.packageCartItems.find((packageCartItem) => packageCartItem == cartItem)) {
                    if (cartItem.isDisplayed) {
                        nonpackageCartItems.push(cartItem);
                    }
                }
            });
            return nonpackageCartItems;
        },
        // Individual Cart Items
        frontWiperCartItemName() {
            return this.getCmsContentForVapsType(partTypeStrings.FRONT_WIPER);
        },
        frontWipersCartItem() {
            let cartItem = null;

            const frontWiperLineItems = this.vaps.filter(
                (vapsLineItem) => vapsLineItem.partType == partTypeStrings.FRONT_WIPER
            );

            if (frontWiperLineItems.length > 0) {
                cartItem = {
                    name: this.frontWiperCartItemName,
                    category: cartItemCategories.VAPS,
                    cartItemType: cartItemTypes.FRONT_WIPERS,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.FRONT_WIPERS
                    ),
                };

                frontWiperLineItems.forEach((lineItem) => {
                    lineItem.cartItemType = cartItem.cartItemType;
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal +=
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0;
                });
            }

            return cartItem;
        },
        rearWiperCartItemName() {
            return this.getCmsContentForVapsType(partTypeStrings.REAR_WIPER);
        },
        rearWipersCartItem() {
            let cartItem = null;

            const rearWiperLineItems = this.vaps.filter(
                (vapsLineItem) => vapsLineItem.partType == partTypeStrings.REAR_WIPER
            );

            if (rearWiperLineItems.length > 0) {
                cartItem = {
                    name: this.rearWiperCartItemName,
                    category: cartItemCategories.VAPS,
                    cartItemType: cartItemTypes.REAR_WIPERS,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.REAR_WIPERS
                    ),
                };

                rearWiperLineItems.forEach((lineItem) => {
                    lineItem.cartItemType = cartItem.cartItemType;
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal +=
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0;
                });
            }

            return cartItem;
        },
        rainRepelCartItemName() {
            return this.getCmsContentForVapsType(partTypeStrings.RAIN_REPEL);
        },
        rainRepelCartItem() {
            let cartItem = null;

            const rainRepelLineItem = this.vaps.find(
                (vapsLineItem) => vapsLineItem.partType == partTypeStrings.RAIN_REPEL
            );

            if (rainRepelLineItem) {
                cartItem = {
                    name: this.getCmsContentForVapsType(partTypeStrings.RAIN_REPEL),
                    category: cartItemCategories.VAPS,
                    cartItemType: cartItemTypes.RAIN_REPEL,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.RAIN_REPEL
                    ),
                };

                rainRepelLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(rainRepelLineItem);

                cartItem.subTotal +=
                    (rainRepelLineItem.kitPrice ?? 0) +
                    (rainRepelLineItem.laborAmount ?? 0) +
                    (rainRepelLineItem.sellingPrice ?? 0);

                cartItem.salesTax += rainRepelLineItem.salesTax ?? 0;
            }

            return cartItem;
        },
        glassPartCartItems() {
            const glassPartCartItems = [];

            if (this.glassParts.length > 0) {
                this.glassParts.forEach((lineItem) => {
                    let cartItem = {
                        name: null,
                        category: cartItemCategories.GLASS_PARTS,
                        cartItemType: cartItemTypes.GLASS_PARTS,
                        isDisplayed: false,
                        isRemovable: false,
                        subTotal:
                            (lineItem.kitPrice ?? 0) +
                            (lineItem.laborAmount ?? 0) +
                            (lineItem.sellingPrice ?? 0),
                        salesTax: lineItem.salesTax ?? 0,
                        lineItems: [],
                        isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                            cartItemTypes.GLASS_PARTS
                        ),
                    };

                    if (lineItem.childParts?.length > 0) {
                        lineItem.childParts.forEach((childPartLineItem) => {
                            cartItem.subTotal +=
                                (childPartLineItem.kitPrice ?? 0) +
                                (childPartLineItem.laborAmount ?? 0) +
                                (childPartLineItem.sellingPrice ?? 0);

                            cartItem.salesTax += childPartLineItem.salesTax;
                        });
                    }

                    glassPartCartItems.push(cartItem);
                });
            }

            return glassPartCartItems;
        },
        recycleFeeCartItemName() {
            return this.getCmsContent("RecycleFeeTextWidget", "Text");
        },
        showRecycleFeeCartItem() {
            if (this.isCashItacNoComp) {
                // CASH, ITAC, NOCOMP ORDERS
                return !this.isRepair;
            } else {
                return false;
            }
        },
        recycleFeeCartItem() {
            let cartItem = null;

            let recycleFeeLineItem = this.supportingItems.find(
                (supportingItem) => supportingItem.partType == partTypeStrings.REPLACE_FEE
            );

            if (!recycleFeeLineItem && this.showRecycleFeeCartItem) {
                recycleFeeLineItem = {
                    partNumber: partTypeStrings.RECYCLE_FEE,
                    partType: partTypeStrings.REPLACE_FEE,
                    laborAmount: 0,
                    kitPrice: 0,
                    sellingPrice: 0,
                    salesTax: 0,
                };
            }

            if (recycleFeeLineItem) {
                cartItem = {
                    name: this.recycleFeeCartItemName,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.REPLACE_FEE,
                    isDisplayed: true,
                    isRemovable: false,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.REPLACE_FEE
                    ),
                };

                recycleFeeLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(recycleFeeLineItem);

                cartItem.subTotal +=
                    (recycleFeeLineItem.kitPrice ?? 0) +
                    (recycleFeeLineItem.laborAmount ?? 0) +
                    (recycleFeeLineItem.sellingPrice ?? 0);

                cartItem.salesTax = recycleFeeLineItem.salesTax ?? 0;
            }

            return cartItem;
        },
        suppliesRepairCartItemName() {
            return this.getCmsContent("SuppliesRepairTextWidget", "Text");
        },
        suppliesRepairCartItem() {
            let cartItem = null;

            const suppliesRepairLineItem = this.supportingItems.find(
                (supportingItem) =>
                    supportingItem.partType == partTypeStrings.REPAIR_FEE &&
                    supportingItem.partNumber != "WSREPAIR"
            );

            if (suppliesRepairLineItem) {
                cartItem = {
                    name: this.suppliesRepairCartItemName,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.SUPPLIES_REPAIR,
                    isDisplayed: true,
                    isRemovable: false,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.SUPPLIES_REPAIR
                    ),
                };

                suppliesRepairLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(suppliesRepairLineItem);

                cartItem.subTotal +=
                    (suppliesRepairLineItem.kitPrice ?? 0) +
                    (suppliesRepairLineItem.laborAmount ?? 0) +
                    (suppliesRepairLineItem.sellingPrice ?? 0);

                cartItem.salesTax = suppliesRepairLineItem.salesTax ?? 0;
            }

            return cartItem;
        },
        isCashItacNoComp() {
            return !this.isInsurance || this.isITAC || this.isNoComp;
        },
        mobileFeeCartItemName() {
            return this.getCmsContent("MobileServiceTextWidget", "Text");
        },
        mobileFeeCartItem() {
            let cartItem = null;
            let showMobileFeeCartItem = false;
            const mobileFeeLineItem = this.supportingItems.find(
                (lineItem) =>
                    lineItem.partType == partTypeStrings.MOBILE_FEE &&
                    lineItem.partNumber == partTypeStrings.MOBILE_FEE
            );

            var mobileTotal =
                (mobileFeeLineItem?.kitPrice ?? 0) +
                (mobileFeeLineItem?.laborAmount ?? 0) +
                (mobileFeeLineItem?.sellingPrice ?? 0);

            if (mobileTotal > 0) {
                if (this.isMSRFeeApplicable) {
                    showMobileFeeCartItem = this.isCashItacNoComp;
                } else {
                    showMobileFeeCartItem = true;
                }
            }

            if (mobileFeeLineItem && showMobileFeeCartItem) {
                cartItem = {
                    name: this.mobileFeeCartItemName,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.MOBILE_FEE,
                    isDisplayed: true,
                    isRemovable: false,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.MOBILE_FEE
                    ),
                };
                mobileFeeLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(mobileFeeLineItem);
                cartItem.subTotal += mobileTotal;
                cartItem.salesTax += mobileFeeLineItem.salesTax ?? 0;
            }
            return cartItem;
        },
        msrFeeCartItemName() {
            return this.getCmsContent("MSRFeeTextWidget", "Text");
        },
        getMsrFeeLineItem() {
            return this.supportingItems.find(
                (lineItem) =>
                    lineItem.partType == partTypeStrings.MOBILE_FEE &&
                    (lineItem.partNumber == partNumberStrings.MOBILE_STATIC_RECAL_FEE ||
                        lineItem.partNumber == partNumberStrings.MOBILE_DUAL_RECAL_FEE)
            );
        },
        msrFeeCartItem() {
            let cartItem = null;
            const msrFeeLineItem = this.getMsrFeeLineItem;
            const shouldCreateMsrFeeCartItem =
                this.isMSRFeeApplicable &&
                (!this.isInsurance || !this.IsMSRFeeCoveredByInsurance) &&
                msrFeeLineItem &&
                this.msrFeeAmount > 0;

            if (shouldCreateMsrFeeCartItem) {
                cartItem = {
                    name: this.msrFeeCartItemName,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.MOBILE_FEE,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: this.IsMSRFeeCoveredByInsurance,
                };
                msrFeeLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(msrFeeLineItem);
                cartItem.subTotal += this.msrFeeAmount;
                cartItem.salesTax += msrFeeLineItem.salesTax ?? 0;
            }
            return cartItem;
        },
        msrFeeAmount() {
            const msrFeeLineItem = this.getMsrFeeLineItem;
            if (!msrFeeLineItem) {
                return 0;
            }
            return (
                msrFeeLineItem.laborAmount + msrFeeLineItem.sellingPrice + msrFeeLineItem.kitPrice
            );
        },
        recyclingToolTipBodyText() {
            return this.getCmsContent("RecycleTextBlock", "Text");
        },
        msrToolTipBodyText() {
            let cmsContentText = this.isInsurance
                ? this.getCmsContent("MSRModal", "BodyText")
                : this.getCmsContent("MSRModal", "BodyText2");
            if (this.isInsurance && cmsContentText) {
                cmsContentText = cmsContentText.replaceAll(
                    "{custom:mobileFee}",
                    formatToUSDollar(this.msrFeeAmount)
                );
                cmsContentText = cmsContentText.replaceAll(
                    "{custom:submittedOrder.policy.insuranceCompanyName}",
                    this.insuranceCompanyName
                );
            }
            return cmsContentText;
        },
        quotePageDiscountCartItemName() {
            return this.getCmsContent("ServicePackageDiscountTextWidget", "Text");
        },
        quotePageDiscountCartItem() {
            let cartItem = null;

            const quotePageDiscountLineItem = this.supportingItems.find(
                (lineItem) => lineItem.partType == partTypeStrings.QUOTE_PAGE_DISCOUNT
            );

            if (quotePageDiscountLineItem) {
                cartItem = {
                    name:
                        this.quotePageDiscountCartItemName +
                        Math.abs(
                            baseMixin.methods.getTotalLineItemPrice(quotePageDiscountLineItem)
                        ),
                    category: cartItemCategories.QUOTE_PAGE_DISCOUNT,
                    cartItemType: cartItemTypes.QUOTE_PAGE_DISCOUNT,
                    isDisplayed: true,
                    isRemovable: false,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: false,
                };

                quotePageDiscountLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(quotePageDiscountLineItem);

                cartItem.subTotal +=
                    (quotePageDiscountLineItem.kitPrice ?? 0) +
                    (quotePageDiscountLineItem.laborAmount ?? 0) +
                    (quotePageDiscountLineItem.sellingPrice ?? 0);

                cartItem.salesTax += quotePageDiscountLineItem.salesTax ?? 0;
            }

            return cartItem;
        },
        otherSupportingItemsCartItem() {
            let cartItem = null;

            const otherSupportingItems = this.supportingItems.filter((item) => {
                return item.partType != partTypeStrings.QUOTE_PAGE_DISCOUNT;
            });
            // Don't include fees they are part of the package total
            let otherSupportingItemsLineItems =
                baseMixin.methods.filterOutFees(otherSupportingItems);

            if (otherSupportingItemsLineItems.length > 0) {
                cartItem = {
                    name: null,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.SUPPORTING_ITEMS,
                    isDisplayed: false,
                    isRemovable: false,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.SUPPORTING_ITEMS
                    ),
                };

                otherSupportingItemsLineItems.forEach((lineItem) => {
                    lineItem.cartItemType = cartItem.cartItemType;
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal +=
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0;
                });
            }

            return cartItem;
        },
        premiumAppointmentDiscountCartItemName() {
            return this.getCmsContent("PremiumAppointmentTextWidget", "Text");
        },
        premiumAppointmentDiscountCartItem() {
            let cartItem = null;

            const premiumAppointmentDiscountLineItem = this.supportingItems.find(
                (lineItem) => lineItem.partType == partTypeStrings.EARLY_BIRD
            );

            if (premiumAppointmentDiscountLineItem) {
                cartItem = {
                    name: this.premiumAppointmentDiscountCartItemName,
                    category: cartItemCategories.SUPPORTING_ITEMS,
                    cartItemType: cartItemTypes.EARLY_BIRD,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(
                        cartItemTypes.EARLY_BIRD
                    ),
                };

                premiumAppointmentDiscountLineItem.cartItemType = cartItem.cartItemType;
                cartItem.lineItems.push(premiumAppointmentDiscountLineItem);

                cartItem.subTotal +=
                    (premiumAppointmentDiscountLineItem.kitPrice ?? 0) +
                    (premiumAppointmentDiscountLineItem.laborAmount ?? 0) +
                    (premiumAppointmentDiscountLineItem.sellingPrice ?? 0);

                cartItem.salesTax += premiumAppointmentDiscountLineItem.salesTax ?? 0;
            }

            return cartItem;
        },
        promoCartItems() {
            const promoCartItems = [];

            // get unique promo codes
            const uniquePromoCodes = [
                ...new Set(
                    this.promos.map((promo) => getPromoCodeWithoutBundleIdentifier(promo.promoCode))
                ),
            ];

            uniquePromoCodes.forEach((promoCode) => {
                // get the codes with the prefix from the promo array
                const promoLineItems = this.promos.filter(
                    (promo) => getPromoCodeWithoutBundleIdentifier(promo.promoCode) == promoCode
                );

                // Create a cart item for each promo
                let cartItem = null;

                cartItem = {
                    name: promoCode,
                    category: cartItemCategories.PROMOS,
                    cartItemType: promoCode,
                    isDisplayed: true,
                    isRemovable: true,
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                    isCoveredByInsurance: cartItemTypesCoveredByInsurance.includes(promoCode),
                };

                promoLineItems.forEach((promoLineItem) => {
                    promoLineItem.cartItemType = cartItem.cartItemType;

                    cartItem.subTotal +=
                        (promoLineItem.kitPrice ?? 0) +
                        (promoLineItem.laborAmount ?? 0) +
                        (promoLineItem.sellingPrice ?? 0);

                    cartItem.salesTax += promoLineItem.salesTax ?? 0;

                    cartItem.lineItems.push(promoLineItem);
                });

                promoCartItems.push(cartItem);
            });

            return promoCartItems;
        },
        showDonationCartItem() {
            const donationLineItem = this.lineItems.supportingItems.find(
                (item) => item.partType === partTypeStrings.DONATION
            );
            return !!donationLineItem;
        },
        donationCartItemName() {
            return this.getCmsContent("DonationCartTextWidget", "Text");
        },
        removeLinkText() {
            return this.getCmsContent("RemoveCartItemTextWidget", "Text");
        },
        recycleFeeText() {
            return this.getCmsContent("RecycleFeeTextWidget", "Text");
        },
        salesTaxText() {
            return this.getCmsContent("SalesTaxTextWidget", "Text");
        },
        amountDueText() {
            return this.getCmsContent("AmountDueTextWidget", "Text");
        },
        orderDetailsText() {
            return this.getCmsContent("OrderDetailsTextWidget", "Text");
        },
        estimateDetailsText() {
            return this.getCmsContent("EstimateDetailsTextWidget", "Text");
        },
        cartHeaderText() {
            if (!this.isInsurance && this.shouldHideRecalibration) {
                return this.estimateDetailsText;
            } else {
                return this.orderDetailsText;
            }
        },
        amountPaidText() {
            return this.getCmsContent("AmountPaidTextWidget", "Text");
        },
        subtotalText() {
            return this.getCmsContent("SubtotalTextWidget", "Text");
        },
        subTotal() {
            if (!this.lineItems || this.lineItems.length < 1) return;
            return this.isInsurance || !this.shouldHideRecalibration
                ? getSubTotal(this.lineItems) // calculate with recal (if on order)
                : getSubTotal(this.lineItemsWithoutRecal); // calculate without recal
        },
        salesTax() {
            if (!this.lineItems || this.lineItems.length < 1) return;

            if (
                this.isInsurance &&
                !this.showCoverageAsVerified &&
                !this.isItac &&
                !this.isNoComp
            ) {
                return 0;
            }

            return this.isInsurance || !this.shouldHideRecalibration
                ? getSalesTax(this.lineItems) // calculate with recal (if on order)
                : getSalesTax(this.lineItemsWithoutRecal); // calculated without recal
        },
        amountDue() {
            if (!this.lineItems || this.lineItems.length < 1) return;
            if (this.showAsPaid) return 0;
            if (this.isInsurance || !this.shouldHideRecalibration) {
                return this.donationCartItem
                    ? getAmountDueWithDonation(this.lineItems, this.donationCartItem)
                    : getAmountDue(this.lineItems);
            } else {
                return this.donationCartItem
                    ? getAmountDueWithDonation(this.lineItemsWithoutRecal, this.donationCartItem)
                    : getAmountDue(this.lineItemsWithoutRecal);
            }
        },
        amountPaid() {
            if (!this.showAsPaid) {
                return 0;
            }

            // unary plus operator to convert string amount to numeric so we can add them together
            var amtPaid = +this.subTotal + +this.salesTax;
            return amtPaid;
        },
        infoIcon() {
            return require(`@/assets/img/icons/question-mark-icon-blue.svg`);
        },
    },
    components: {
        textBlock,
        textLink,
        promoModalQuestion,
        removeMsrFeeModal,
        toolTip,
    },
};
</script>

<style lang="scss">
.cart {
    margin-bottom: 1rem;

    h5 {
        border-bottom: 1px solid $gray-500;
        color: $black;
    }
    .modal-body {
        h5 {
            text-align: center;
            border-bottom: none;
        }
    }
    .border-bottom {
        color: $gray;
    }
    .label {
        color: $black;
        font-weight: 500;
        line-height: 1.625;
    }
    .non-collapsible {
        .amount-due {
            display: none;
        }
    }
    .amount-due {
        color: $green;

        &.larger {
            font-size: 1.25rem;
        }
    }
    .cart-panel {
        max-height: 0;
        transition: all 350ms ease-in;
        overflow: hidden;
        visibility: hidden;
        color: $gray-600;
    }
    .price-table {
        div {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 1.5rem;
            &:last-child {
                background-color: $gray-100;
                > span:last-of-type {
                    color: $green;
                }
            }
        }
        .struck-out-price {
            text-decoration: line-through;
            padding-left: 0.5rem;
        }
        .packaged-cart-item {
            padding-left: 2.5rem;
            align-items: center;
            span {
                display: flex;
                font-size: 0.875rem;
                &:nth-child(2) {
                    justify-content: flex-end;
                }
                &:last-child {
                    justify-content: flex-end;
                }
                &.promo {
                    text-transform: uppercase;
                }
            }
            a {
                font-size: 0.875rem;
                text-decoration: none;
                line-height: 1.75;
            }
        }
        .non-packaged-cart-item {
            a {
                line-height: 1.625;
            }
        }

        // Custom order/wrap for removable nonpackaged Cart Items
        .removable-cart-item {
            flex-wrap: wrap;
            span {
                display: flex;
                justify-content: space-between;
            }
            a {
                order: 3;
                margin-right: 100%;
                text-decoration: none;

                &#msr-fee-cartItem {
                    margin: 0 0 0 0.2rem;
                }
            }
        }
        .package-type,
        .service-type,
        .deductible {
            align-items: center;
        }
        .sub-total,
        .sales-tax,
        .amount-due,
        .amount-paid,
        .donation-amount {
            font-family: UrbanistSemibold;
            color: $black;
        }
        .sub-total {
            border-top: 1px solid $gray-600;
        }
        .service-type,
        .deductible {
            .text-block {
                background: transparent;
                margin-top: 0;
                padding: 0;
                width: 50%;
            }
        }
    }
    .insurance-company-name {
        margin-top: 0.5rem;
    }
    .vin-toggle {
        &:not(.non-collapsible) {
            &:after {
                content: "";
                transition: all 0.5s ease;
                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'%3E%3Cpath fill='%230070D1' d='M12 0a12 12 0 1 0 0 24 12 12 0 0 0 0-24Zm6.113 11.28-5.52 5.52a.84.84 0 0 1-1.186 0l-5.52-5.52a.843.843 0 1 1 1.186-1.2L12 15.012l4.927-4.932a.843.843 0 1 1 1.186 1.2Z'/%3E%3C/svg%3E");
                background-repeat: no-repeat;
                background-position: right center;
                width: 24px;
                height: 24px;
                display: inline-flex;
                position: relative;
                right: 0.75rem;
                margin: 0.5rem 0 0.5rem 1rem;
                cursor: pointer;
            }
            &.expanded:after {
                transform: rotate(180deg);
            }
        }

        &.expanded + .cart-panel {
            max-height: 650px;
            transition: all 150ms ease-in;
            overflow: hidden;
            padding: 1rem 0 0.5rem;
            visibility: visible;
        }

        &.non-collapsible {
            & > a {
                cursor: default;
            }
        }

        a {
            font-family: UrbanistSemibold;
            text-decoration: none;
        }
    }
    .applied-promo-tag {
        span {
            color: $green-700;
            font-weight: 500;
            padding: 2px 8px;
            background-color: $green-100;
            border-radius: 12px;

            &.promo-code {
                text-transform: uppercase;
                padding: 0;
            }
        }
    }
}
.payment-method-question {
    .question-text {
        margin: 1rem 0 0.5rem 0;
    }
    span {
        line-height: 24px;
    }
}
</style>
