/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import cn from "../../global/lib/cn";
import { scrollIntoContainerView } from "../../global/lib/scroll-into-container-view";
import { VehicleInfoLayout } from "../../features/vehicle-info-layout/index";
import { smartInvokable } from "../../features/blazor-ref/index";
import { setVehicleLookupData, setVehicleLookupErrorState } from "../../features/vehicle-lookup-component/index";
import { getLocaleLanguage, getSharedLocal, sharedLocalesSchema } from "../../features/multi-lingual/index";
import { ClaimableItem } from "./components/claimable-item";
import { ClaimableItemPopover } from "./components/claimable-item-popover";
import { ClaimableTraceModal } from "./components/claimable-trace-modal";
import dynamicClaimSchema from "../../locales/vehicleLookup/claimableItems/type";
import { PrintIcon } from "../../global/assets/print-icon";
import { ActivationIcon } from "../../global/assets/activation-icon";
import { EmptyTableIcon } from "../../global/assets/empty-table-icon";
export class VehicleClaimableItems {
    constructor() {
        // #region Localization
        this.language = 'en';
        this.locale = Object.assign({ sharedLocales: sharedLocalesSchema.getDefault() }, dynamicClaimSchema.getDefault());
        // #endregion
        // #region Vehicle info layout prop
        this.coreOnly = false;
        this.disableVinValidation = false;
        this.headers = {};
        this.queryString = '';
        this.uploadMultipleDocumentsAtTheForm = true;
        this.isError = false;
        this.isLoading = false;
        this.maximumDocumentFileSizeInMb = 30;
        this.claimEndPoint = 'api/vehicle/swift-claim';
        this.showTrace = false;
        this.activeTab = '';
        this.showPrintBox = false;
        this.tabAnimationLoading = false;
        this.lastSuccessfulClaimResponse = null;
        this.showClaimableItemPopover = false;
        this.tabs = [];
        this.popoverTarget = { centerX: 0, topY: 0, bottomY: 0 };
        this.popoverHeight = 0;
        this.popoverBodyContentHeight = 0;
        this.popoverContentFading = false;
        this.popoverFadingOut = false;
        this.showTraceModal = false;
        this.traceModalFadingOut = false;
        this.isLoadingTrace = false;
        this.getServiceItems = () => {
            var _a, _b, _c, _d, _e;
            if (!((_b = (_a = this.vehicleLookup) === null || _a === void 0 ? void 0 : _a.serviceItems) === null || _b === void 0 ? void 0 : _b.length))
                return [];
            if (!((_c = this.tabs) === null || _c === void 0 ? void 0 : _c.length))
                return (_d = this.vehicleLookup) === null || _d === void 0 ? void 0 : _d.serviceItems;
            return (_e = this.vehicleLookup) === null || _e === void 0 ? void 0 : _e.serviceItems.filter(serviceItem => { var _a; return ((_a = serviceItem === null || serviceItem === void 0 ? void 0 : serviceItem.group) === null || _a === void 0 ? void 0 : _a.name) === this.activeTab; });
        };
        this.parseGroupData = (vehicleLookup) => {
            var _a;
            if ((_a = vehicleLookup === null || vehicleLookup === void 0 ? void 0 : vehicleLookup.serviceItems) === null || _a === void 0 ? void 0 : _a.length) {
                let orderedGroups = [];
                const unOrderedGroups = [];
                vehicleLookup.serviceItems.forEach(({ group }) => {
                    if (!(group === null || group === void 0 ? void 0 : group.name))
                        return;
                    if ([...orderedGroups, ...unOrderedGroups].find(g => (g === null || g === void 0 ? void 0 : g.name) === (group === null || group === void 0 ? void 0 : group.name)))
                        return;
                    if (group === null || group === void 0 ? void 0 : group.isDefault)
                        this.activeTab = group === null || group === void 0 ? void 0 : group.name;
                    if (typeof (group === null || group === void 0 ? void 0 : group.tabOrder) === 'number')
                        orderedGroups.push(group);
                    else
                        unOrderedGroups.push(group);
                });
                if (!!unOrderedGroups.length || !!orderedGroups.length) {
                    orderedGroups = orderedGroups.sort((a, b) => a.tabOrder - b.tabOrder);
                    this.tabs = [...orderedGroups, ...unOrderedGroups];
                    if (!this.activeTab)
                        this.activeTab = this.tabs[0].name;
                }
                else {
                    this.tabs = [];
                    this.activeTab = '';
                }
            }
            else {
                this.tabs = [];
                this.activeTab = '';
            }
            return vehicleLookup;
        };
        this.updateProgressBar = async (payload) => {
            var _a, _b;
            // payload indicates its not a fresh list rather it is an update to current one
            if (!payload) {
                // hard reset of the bar
                this.progressBar.style.transitionDuration = '0s';
                this.progressBar.style.opacity = '0';
                this.progressBar.style.width = '0%';
                // apply changes
                await new Promise(r => setTimeout(r, 10));
            }
            this.progressBar.style.transitionDuration = '1s';
            this.progressBar.style.opacity = '1';
            if (!this.vehicleLookup)
                return;
            if (!!((_a = this.tabs) === null || _a === void 0 ? void 0 : _a.length) && this.tabs.find(tab => tab.name === this.activeTab) && !((_b = this.tabs.find(tab => tab.name === this.activeTab)) === null || _b === void 0 ? void 0 : _b.isSequential))
                return;
            const serviceItems = this.getServiceItems();
            const firstPendingItemIndex = serviceItems.findIndex(x => x.status === 'pending');
            if (firstPendingItemIndex !== -1) {
                const pendingItemRef = this.el.shadowRoot.querySelectorAll('.claimable-item')[firstPendingItemIndex];
                const progressLaneRef = this.el.shadowRoot.querySelector('.progress-lane');
                const { left: pendingItemLeftOffset } = pendingItemRef.getBoundingClientRect();
                const { width: progressLaneWidth, left: progressLeftOffset } = progressLaneRef.getBoundingClientRect();
                const offsetToLeftRatio = ((pendingItemLeftOffset - progressLeftOffset) / progressLaneWidth) * 100;
                this.progressBar.style.width = `${offsetToLeftRatio.toFixed(2)}%`;
                if (firstPendingItemIndex === serviceItems.length - 1)
                    this.claimableItemsBox.scrollTo({
                        left: this.claimableItemsBox.scrollWidth,
                        behavior: 'smooth',
                    });
                else
                    scrollIntoContainerView(pendingItemRef, this.claimableItemsBox);
            }
            else if (!(serviceItems.length === 0 || serviceItems.filter(x => x.status === 'activationRequired').length === serviceItems.length)) {
                this.progressBar.style.width = '100%';
                this.claimableItemsBox.scrollTo({
                    left: this.claimableItemsBox.scrollWidth,
                    behavior: 'smooth',
                });
            }
        };
        this.onActiveTabChange = ({ label }) => {
            this.tabAnimationLoading = true;
            clearTimeout(this.tabAnimationTimeoutRef);
            this.tabAnimationTimeoutRef = setTimeout(() => {
                this.activeTab = label;
                // wait for jsx update
                setTimeout(() => {
                    this.tabAnimationLoading = false;
                    this.updateProgressBar();
                }, 50);
            }, 750);
        };
        this.activateClaimItem = () => {
            if (this.activate)
                this.activate(this.vehicleLookup);
        };
        this.printLastClaimResponse = () => {
            if (this.print) {
                this.print(this.lastSuccessfulClaimResponse);
            }
            else {
                if (this.lastSuccessfulClaimResponse.PrintURL) {
                    window.open(this.lastSuccessfulClaimResponse.PrintURL, '_blank').focus();
                }
            }
        };
        this.updatePopoverLocation = () => {
            if (!this.popoverAnchorEl)
                return;
            const { left, right, top, bottom } = this.popoverAnchorEl.getBoundingClientRect();
            this.popoverTarget = { centerX: (left + right) / 2, topY: top, bottomY: bottom };
        };
        this.measurePopoverHeight = () => {
            var _a;
            const body = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.popover-body');
            if (body && body.offsetHeight > 0)
                this.popoverHeight = body.offsetHeight;
        };
        this.measurePopoverContentHeight = () => {
            var _a;
            const inner = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.popover-body-inner');
            if (!inner)
                return 0;
            // Use getBoundingClientRect for sub-pixel precision and ceil to avoid undershooting at
            // fractional browser zoom (e.g. 80%, where offsetHeight may round down by 1px and clip the bottom).
            return Math.ceil(inner.getBoundingClientRect().height);
        };
        this.setClaimableItemPopover = (showPopover, claimableItem, anchorEl) => {
            clearTimeout(this.popoverCloseTimeoutRef);
            clearTimeout(this.popoverHideTimeoutRef);
            if (showPopover) {
                // Called without args (e.g. popover hover) — just keep it open by cancelling close timers.
                if (!anchorEl || !claimableItem) {
                    if (this.popoverFadingOut) {
                        this.popoverFadingOut = false;
                        this.showClaimableItemPopover = true;
                    }
                    return;
                }
                // The popover is "still active" if it's open OR mid-fade-out. Don't tear down state in either case.
                const wasActive = this.showClaimableItemPopover || this.popoverFadingOut;
                const sameItem = wasActive && this.selectedClaimItem === claimableItem;
                this.popoverAnchorEl = anchorEl;
                if (sameItem) {
                    // Re-hovering the same item that's still showing/fading — just bring it back, no state churn.
                    this.popoverFadingOut = false;
                    this.showClaimableItemPopover = true;
                    return;
                }
                clearTimeout(this.popoverContentSwapTimeoutRef);
                if (wasActive) {
                    // Switching to a different item while still active: slide + cross-fade content.
                    this.popoverBodyContentHeight = this.measurePopoverContentHeight();
                    this.popoverContentFading = true;
                    this.popoverFadingOut = false;
                    this.showClaimableItemPopover = true;
                    this.updatePopoverLocation();
                    this.popoverContentSwapTimeoutRef = setTimeout(() => {
                        this.selectedClaimItem = claimableItem;
                        requestAnimationFrame(() => {
                            this.popoverBodyContentHeight = this.measurePopoverContentHeight();
                            this.popoverContentFading = false;
                            this.measurePopoverHeight();
                        });
                    }, VehicleClaimableItems.POPOVER_CONTENT_FADE_MS);
                }
                else {
                    // Truly fresh open. Two-frame dance: set position while still hidden, then flip aria-expanded
                    // next frame so the opacity fade-in doesn't drag a position transition along with it.
                    this.popoverContentFading = false;
                    this.popoverBodyContentHeight = 0;
                    this.selectedClaimItem = claimableItem;
                    this.updatePopoverLocation();
                    requestAnimationFrame(() => {
                        this.showClaimableItemPopover = true;
                        requestAnimationFrame(() => this.measurePopoverHeight());
                    });
                }
            }
            else {
                this.popoverCloseTimeoutRef = setTimeout(() => {
                    clearTimeout(this.popoverContentSwapTimeoutRef);
                    this.showClaimableItemPopover = false;
                    this.popoverFadingOut = true;
                    this.popoverContentFading = false;
                    this.popoverHideTimeoutRef = setTimeout(() => {
                        this.popoverFadingOut = false;
                        this.popoverBodyContentHeight = 0;
                    }, VehicleClaimableItems.POPOVER_FADE_OUT_MS);
                }, VehicleClaimableItems.POPOVER_CLOSE_DELAY_MS);
            }
        };
        this.onPopoverMouseEnter = () => {
            // Cancel any pending close + recover from fade-out if needed.
            this.setClaimableItemPopover(true);
        };
        this.onPopoverMouseLeave = () => {
            this.setClaimableItemPopover(false);
        };
        this.openTraceModal = async () => {
            var _a, _b;
            if (!((_a = this.vehicleLookup) === null || _a === void 0 ? void 0 : _a.vin))
                return;
            clearTimeout(this.traceFadeOutTimeoutRef);
            this.traceModalFadingOut = false;
            this.showTraceModal = true;
            this.isLoadingTrace = true;
            this.traceError = undefined;
            this.traceHtml = undefined;
            // Match the claim-form pattern: lock host page scroll so the only scrollbar is the iframe's.
            document.body.style.overflow = 'hidden';
            this.traceCloseListener = (event) => {
                if (event.key === 'Escape')
                    this.closeTraceModal();
            };
            window.addEventListener('keydown', this.traceCloseListener);
            (_b = this.traceAbortController) === null || _b === void 0 ? void 0 : _b.abort();
            this.traceAbortController = new AbortController();
            try {
                const traceQuery = [this.queryString, 'trace=html'].filter(Boolean).join('&');
                const url = `${this.baseUrl}${this.vehicleLookup.vin}${traceQuery ? `?${traceQuery}` : ''}`;
                const response = await fetch(url, {
                    method: 'GET',
                    headers: Object.assign({ Accept: 'text/html' }, (this.headers || {})),
                    signal: this.traceAbortController.signal,
                });
                if (!response.ok)
                    throw new Error(`HTTP ${response.status}`);
                const html = await response.text();
                if (!this.showTraceModal)
                    return;
                this.traceHtml = html;
                this.isLoadingTrace = false;
            }
            catch (error) {
                if ((error === null || error === void 0 ? void 0 : error.name) === 'AbortError')
                    return;
                console.error('Trace fetch failed', error);
                this.isLoadingTrace = false;
                this.traceError = this.locale.traceFailed;
            }
        };
        this.closeTraceModal = () => {
            var _a;
            if (!this.showTraceModal && !this.traceModalFadingOut)
                return;
            (_a = this.traceAbortController) === null || _a === void 0 ? void 0 : _a.abort();
            this.showTraceModal = false;
            this.traceModalFadingOut = true;
            document.body.style.overflow = 'auto';
            if (this.traceCloseListener) {
                window.removeEventListener('keydown', this.traceCloseListener);
                this.traceCloseListener = undefined;
            }
            clearTimeout(this.traceFadeOutTimeoutRef);
            this.traceFadeOutTimeoutRef = setTimeout(() => {
                this.traceModalFadingOut = false;
                this.isLoadingTrace = false;
                this.traceError = undefined;
                this.traceHtml = undefined;
            }, VehicleClaimableItems.TRACE_FADE_OUT_MS);
        };
        this.handleClaim = async (documents, payload) => {
            try {
                const formData = new FormData();
                payload.vin = this.vehicleLookup.vin;
                payload.saleInformation = this.vehicleLookup.saleInformation;
                payload.serviceItem = this.claimForm.item;
                payload.identifiers = this.vehicleLookup.identifiers;
                payload.vehicleVariantInfo = this.vehicleLookup.vehicleVariantInfo;
                payload.vehicleSpecification = this.vehicleLookup.vehicleSpecification;
                formData.append('payload', JSON.stringify(payload));
                if (documents && documents.length > 0) {
                    documents.forEach(doc => {
                        formData.append('document', doc);
                    });
                }
                await new Promise((resolve, reject) => {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', this.claimEndPoint);
                    Object.entries(this.headers || {}).forEach(([key, value]) => {
                        xhr.setRequestHeader(key, value);
                    });
                    xhr.upload.onprogress = e => {
                        if (e.lengthComputable)
                            this.claimForm.setFileUploadProgression(Math.round((e.loaded / e.total) * 100));
                    };
                    xhr.onload = () => {
                        if (xhr.status === 200) {
                            try {
                                const responseData = JSON.parse(xhr.responseText);
                                this.completeClaim(responseData);
                                resolve();
                            }
                            catch (parseError) {
                                console.error('Response is not valid JSON', {
                                    rawResponse: xhr.responseText,
                                    error: parseError,
                                });
                                reject(new Error('Upload succeeded but response is not valid JSON'));
                            }
                            resolve();
                        }
                        else {
                            try {
                                const responseData = JSON.parse(xhr.responseText);
                                const error = new Error(responseData.Message);
                                error.serverMessage = responseData.Message;
                                reject(error);
                            }
                            catch (_a) {
                                reject(new Error(`Upload failed with status ${xhr.status}`));
                            }
                        }
                    };
                    xhr.onerror = e => {
                        console.log(e);
                        reject(new Error('Network error'));
                    };
                    xhr.send(formData);
                });
            }
            catch (error) {
                alert((error === null || error === void 0 ? void 0 : error.serverMessage) || this.locale.sharedLocales.errors.requestFailedPleaseTryAgainLater);
                throw new Error(error);
            }
        };
        this.handleDevClaim = async (documents) => {
            try {
                if (documents && documents.length > 0) {
                    this.claimForm.setFileUploadProgression(0);
                    let uploadChunks = 20;
                    for (let index = 0; index < uploadChunks; index++) {
                        const uploadPercentage = Math.round(((index + 1) / uploadChunks) * 100);
                        await new Promise(r => setTimeout(r, 200));
                        this.claimForm.setFileUploadProgression(uploadPercentage);
                    }
                }
                await new Promise(r => setTimeout(r, 1000));
                this.completeClaim({ Success: true, ID: '11223344', PrintURL: 'http://localhost/test/print/1122' });
            }
            catch (error) {
                alert(this.locale.sharedLocales.errors.requestFailedPleaseTryAgainLater);
                throw new Error(error);
            }
        };
    }
    async componentWillLoad() {
        await this.changeLanguage(this.language);
    }
    async changeLanguage(newLanguage) {
        const [sharedLocales, locale] = await Promise.all([getSharedLocal(newLanguage), getLocaleLanguage(newLanguage, 'vehicleLookup.claimableItems', dynamicClaimSchema)]);
        this.locale = Object.assign({ sharedLocales }, locale);
    }
    async setMockData(newMockData) {
        this.mockData = newMockData;
    }
    async fetchVin(newData, headers = {}) {
        const beforeAssignment = async (vehicleLookup) => {
            this.showPrintBox = false;
            await this.parseGroupData(vehicleLookup);
            return vehicleLookup;
        };
        await setVehicleLookupData(this, newData, headers, { beforeAssignment });
    }
    async setErrorMessage(message) {
        setVehicleLookupErrorState(this, message);
    }
    onLoadingChange(newValue) {
        smartInvokable.bind(this)(this.loadingStateChange, newValue);
    }
    async setBlazorRef(newBlazorRef) {
        this.blazorRef = newBlazorRef;
    }
    async componentDidLoad() {
        this.progressBar = this.el.shadowRoot.querySelector('.progress-bar');
        this.claimForm = this.el.shadowRoot.querySelector('.vehicle-item-claim-form');
        this.claimableItemsBox = this.el.shadowRoot.querySelector('.claimable-items-box');
        window.addEventListener('resize', this.updateProgressBar);
        if (this.claimableItemsBox)
            this.claimableItemsBox.addEventListener('scroll', this.updatePopoverLocation);
        window.addEventListener('scroll', this.updatePopoverLocation);
        window.addEventListener('resize', this.updatePopoverLocation);
        requestAnimationFrame(() => this.measurePopoverHeight());
    }
    async disconnectedCallback() {
        var _a;
        window.removeEventListener('resize', this.updateProgressBar);
        if (this.claimableItemsBox)
            this.claimableItemsBox.removeEventListener('scroll', this.updatePopoverLocation);
        window.removeEventListener('scroll', this.updatePopoverLocation);
        window.removeEventListener('resize', this.updatePopoverLocation);
        clearTimeout(this.popoverCloseTimeoutRef);
        clearTimeout(this.popoverHideTimeoutRef);
        clearTimeout(this.popoverContentSwapTimeoutRef);
        clearTimeout(this.traceFadeOutTimeoutRef);
        if (this.traceCloseListener)
            window.removeEventListener('keydown', this.traceCloseListener);
        (_a = this.traceAbortController) === null || _a === void 0 ? void 0 : _a.abort();
        if (this.showTraceModal || this.traceModalFadingOut)
            document.body.style.overflow = 'auto';
    }
    async onVehicleChange() {
        // wait for jsx update
        setTimeout(() => {
            this.updateProgressBar();
        }, 50);
    }
    async openTrace() {
        await this.openTraceModal();
    }
    async completeClaim(response) {
        const serviceItems = this.getServiceItems();
        const item = this.selectedClaimItem;
        const serviceDataClone = JSON.parse(JSON.stringify(serviceItems));
        const index = serviceItems.indexOf(item);
        const pendingItemsBefore = serviceDataClone.slice(0, index).filter(x => x.status === 'pending');
        serviceDataClone[index].claimable = false;
        serviceDataClone[index].status = 'processed';
        pendingItemsBefore.forEach(function (otherItem) {
            otherItem.status = 'cancelled';
        });
        const vehicleDataClone = JSON.parse(JSON.stringify(this.vehicleLookup));
        vehicleDataClone.serviceItems = serviceDataClone;
        this.vehicleLookup = JSON.parse(JSON.stringify(vehicleDataClone));
        if (response.PrintURL)
            this.showPrintBox = true;
        this.lastSuccessfulClaimResponse = response;
    }
    async claim(item) {
        var _a;
        this.selectedClaimItem = item;
        this.claimForm.item = item;
        this.claimForm.vin = (_a = this.vehicleLookup) === null || _a === void 0 ? void 0 : _a.vin;
        this.claimForm.handleClaiming = this.isDev ? this.handleDevClaim.bind(this) : this.handleClaim.bind(this);
        this.claimForm.open();
    }
    // #endregion
    render() {
        var _a, _b, _c, _d, _e;
        const serviceItems = this.getServiceItems();
        const isNoServicesAvailable = !this.isLoading && this.vehicleLookup && !serviceItems.length;
        const hideTabs = this.isLoading || this.isError || !this.tabs.length || !serviceItems.length;
        const tabs = this.tabs.map(group => group.name);
        const hasInactiveItems = (_c = (_b = (_a = this.vehicleLookup) === null || _a === void 0 ? void 0 : _a.warranty) === null || _b === void 0 ? void 0 : _b.activationIsRequired) !== null && _c !== void 0 ? _c : false;
        return (h(Host, { key: 'd3caa4a2aa5414a3f0825d3807bfc2153b60074a', translate: "no" }, h("vehicle-item-claim-form", { key: 'f61a397b41a3f9955512861a97c97e2b926de706', class: "vehicle-item-claim-form", maximumDocumentFileSizeInMb: this.maximumDocumentFileSizeInMb, uploadMultipleDocuments: this.uploadMultipleDocumentsAtTheForm, locale: Object.assign({ sharedLocales: this.locale.sharedLocales }, this.locale.claimForm) }), h(ClaimableItemPopover, { key: '49462b52f6f898a5cc27cf9640d63735e0ef279b', locale: this.locale, claim: this.claim.bind(this), item: this.selectedClaimItem, showPopover: this.showClaimableItemPopover, target: this.popoverTarget, popoverHeight: this.popoverHeight, fadingOut: this.popoverFadingOut, contentFading: this.popoverContentFading, bodyContentHeight: this.popoverBodyContentHeight, onMouseEnter: this.onPopoverMouseEnter, onMouseLeave: this.onPopoverMouseLeave }), h(ClaimableTraceModal, { key: '42f7dca429dc8c49c992cc2ccbcc6a9496e1d460', isOpen: this.showTraceModal, fadingOut: this.traceModalFadingOut, isLoading: this.isLoadingTrace, errorMessage: this.traceError, vin: (_d = this.vehicleLookup) === null || _d === void 0 ? void 0 : _d.vin, traceHtml: this.traceHtml, locale: this.locale, onClose: this.closeTraceModal }), h(VehicleInfoLayout, { key: 'e2986d23a18d6d3d300b2d4b4741fcdc3cb7c1f9', isError: this.isError, coreOnly: this.coreOnly, header: (_e = this.vehicleLookup) === null || _e === void 0 ? void 0 : _e.vin, direction: this.locale.sharedLocales.direction, isLoading: this.isLoading || this.tabAnimationLoading, errorMessage: this.locale.sharedLocales.errors[this.errorMessage] || this.locale.sharedLocales.errors.wildCard, headerRight: this.showTrace && this.vehicleLookup && !this.isLoading && !this.tabAnimationLoading && !this.isError ? (h("button", { type: "button", class: "trace-trigger-button", title: this.locale.viewTrace, "aria-label": this.locale.viewTrace, onClick: this.openTraceModal }, h("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("circle", { cx: "6", cy: "19", r: "3" }), h("path", { d: "M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15" }), h("circle", { cx: "18", cy: "5", r: "3" })))) : null }, h("div", { key: '08fcb9eb25e3149a3e79d19a6d295344d3c96356', dir: "ltr", class: cn('relative flex items-center h-[320px] transition-all duration-300', { loading: this.isLoading || this.tabAnimationLoading }) }, h("div", { key: '342a066dc9319172faa575899f30dde8f950d74c', dir: this.locale.sharedLocales.direction, class: "absolute top-0 z-10 w-full pt-[16px]" }, h("div", { key: 'a42daeb204b3d3bf93520ed6674a784026cb89f5', class: cn('duration-300', { 'translate-y-[-50%] opacity-0': hideTabs }) }, h("shift-tabs", { key: '45495b1210d640ddda04e2a18ee8542cd57e8611', activeTabLabel: this.activeTab, changeActiveTab: this.onActiveTabChange, tabs: tabs }))), h("div", { key: '117757cfd71a6c49f7b24c442064f6f6dc121a0b', class: cn('absolute w-[calc(100%-60px)] left-[30px] progress-container-style opacity-0', { 'opacity-100': this.isLoading || this.tabAnimationLoading }) }, h("div", { key: '868c54e72e9d354286a99df2876a4a6b56e909f1', class: "w-full h-full rounded-[4px] overflow-x-hidden absolute left-0 top-0" }, h("div", { key: '21f945dfdc44ce498bcfa4da2e0ec6cea77693c3', class: "absolute opacity-0 bg-[#1a1a1a] w-[150%] h-full" }), h("div", { key: 'fbae617b9aa07d485a3436fdc77543f572982d27', class: "absolute h-full bg-[linear-gradient(to_bottom,_#428bca_0%,_#3071a9_100%)] lane-inc" }), h("div", { key: 'ac3cc1c839b81f50a14f47f80905b3612bf4287f', class: "absolute h-full bg-[linear-gradient(to_bottom,_#428bca_0%,_#3071a9_100%)] lane-dec" }))), h("div", { key: 'bc22ec732e09fdae48374bd76947eaf1638a5f10', dir: this.locale.sharedLocales.direction, class: cn('absolute w-[90%] z-10 pointer-events-none border opacity-0 translate-y-[-5px] scale-[70%] text-[#8a6d3b] bg-[#fcf8e3] border-[#faebcc] p-[25px] text-[16px] rounded-[6px] flex items-center justify-between left-1/2 -translate-x-1/2 h-10 bottom-[40px] transition duration-500', {
                'opacity-100 pointer-events-auto translate-y-0 scale-100': !this.isLoading && this.vehicleLookup && !this.tabAnimationLoading && (hasInactiveItems || this.showPrintBox),
            }) }, h("span", { key: 'cf812670c5c79d6e3e814f0e5a722e9b5cf9cf71', class: "font-semibold" }, this.showPrintBox ? this.locale.successFulClaimMessage : this.locale.warrantyAndServicesNotActivated), h("button", { key: '38209f4cd4250ce6803466167d69a481b6c0b683', class: "claim-button", onClick: this.showPrintBox ? this.printLastClaimResponse : this.activateClaimItem }, this.showPrintBox ? h(PrintIcon, { class: "size-[30px] duration-200" }) : h(ActivationIcon, { class: "size-[30px] duration-200" }), h("span", { key: 'bbc88b1bd71c8e58ab1886850d4c2f6f30a6f940' }, this.showPrintBox ? this.locale.print : this.locale.activateNow))), h("div", { key: 'c9c1e147ff75660beef1d656638d18ee9dfaa202', class: "claimable-items-box px-[30px] min-w-full relative overflow-x-scroll h-full overflow-y-hidden" }, h("div", { key: '4635cc72f1ed07e343cd8695616c88d4b4abbb45', class: "flex relative w-fit min-w-full items-center h-full [&_*]:shrink-0 gap-[250px] justify-between" }, h("div", { key: '36f74099f37b88a5599a3692c21775a547bc1c7a', class: cn('progress-container-style progress-lane absolute overflow-hidden w-[calc(100%-0px)] translate-y-0 opacity-100', {
                'opacity-0': this.isLoading || this.tabAnimationLoading || isNoServicesAvailable || !this.vehicleLookup,
            }) }, h("div", { key: 'a266d644f57943497fd43618ecda14c119662b3d', part: "progress-bar", class: "progress-bar transition-all w-1/2 h-full bg-[linear-gradient(to_bottom,_#428bca_0%,_#3071a9_100%)]" })), h("div", { key: '0b126303fdda145cc362750125be5592ac690fb8', class: "ml-[-125px]" }), serviceItems.map((item, idx) => (h(ClaimableItem, { item: item, locale: this.locale, setClaimableItemPopover: this.setClaimableItemPopover, addStatusClass: item.status !== 'pending' || serviceItems.findIndex(i => i.status === 'pending') === idx }))), h("div", { key: '1f88b2a4e4ba3912cd7b6092f07f515e06d6e300', class: "ml-[-125px]" })), h("div", { key: '6f7661597f474a52840ee8f0b686c8ce713c774e', dir: this.locale.sharedLocales.direction, class: cn('absolute top-0 left-0 pointer-events-none size-full box-content flex flex-col justify-center opacity-0 transition duration-500 items-center text-slate-700', {
                'opacity-100 scale-100': isNoServicesAvailable,
            }) }, h(EmptyTableIcon, { key: '177d9d76ab79152283bd254d5c44d3e9c9b5963c', class: "size-[90px]" }), h("div", { key: 'aa28ecc8afc28f74b01edbcb4ae93c3647a960ca', class: "text-[22px]" }, this.locale.sharedLocales.errors.noServiceAvailable)))))));
    }
    static get is() { return "vehicle-claimable-items"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["vehicle-claimable-items.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["vehicle-claimable-items.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": false,
                "complexType": {
                    "original": "LanguageKeys",
                    "resolved": "\"ar\" | \"en\" | \"ku\" | \"ru\"",
                    "references": {
                        "LanguageKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::LanguageKeys"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'en'"
            },
            "coreOnly": {
                "type": "boolean",
                "attribute": "core-only",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "isDev": {
                "type": "boolean",
                "attribute": "is-dev",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "disableVinValidation": {
                "type": "boolean",
                "attribute": "disable-vin-validation",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "baseUrl": {
                "type": "string",
                "attribute": "base-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "headers": {
                "type": "unknown",
                "attribute": "headers",
                "mutable": false,
                "complexType": {
                    "original": "object",
                    "resolved": "object",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            },
            "queryString": {
                "type": "string",
                "attribute": "query-string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "uploadMultipleDocumentsAtTheForm": {
                "type": "boolean",
                "attribute": "upload-multiple-documents-at-the-form",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "errorCallback": {
                "type": "string",
                "attribute": "error-callback",
                "mutable": false,
                "complexType": {
                    "original": "BlazorInvokableFunction<(errorMessage: ErrorKeys) => void>",
                    "resolved": "((errorMessage: OptionalKeys<{ noBaseUrl: string; invalidVin: string; vinNumberRequired: string; partNumberRequired: string; wrongResponseFormat: string; noPartsFound: string; noServiceAvailable: string; wrongFormStructure: string; wildCard: string; requestFailedPleaseTryAgainLater: string; }>) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        },
                        "ErrorKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::ErrorKeys"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadingStateChange": {
                "type": "string",
                "attribute": "loading-state-change",
                "mutable": false,
                "complexType": {
                    "original": "BlazorInvokableFunction<(isLoading: boolean) => void>",
                    "resolved": "((isLoading: boolean) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadedResponse": {
                "type": "string",
                "attribute": "loaded-response",
                "mutable": false,
                "complexType": {
                    "original": "BlazorInvokableFunction<(response: VehicleLookupDTO) => void>",
                    "resolved": "((response: VehicleLookupDTO) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        },
                        "VehicleLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/vehicle-lookup/vehicle-lookup-dto",
                            "id": "src/global/types/generated/vehicle-lookup/vehicle-lookup-dto.ts::VehicleLookupDTO"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "print": {
                "type": "unknown",
                "attribute": "print",
                "mutable": false,
                "complexType": {
                    "original": "(claimResponse: any) => void",
                    "resolved": "(claimResponse: any) => void",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "maximumDocumentFileSizeInMb": {
                "type": "number",
                "attribute": "maximum-document-file-size-in-mb",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "30"
            },
            "claimEndPoint": {
                "type": "string",
                "attribute": "claim-end-point",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'api/vehicle/swift-claim'"
            },
            "activate": {
                "type": "unknown",
                "attribute": "activate",
                "mutable": false,
                "complexType": {
                    "original": "(vehicleInformation: VehicleLookupDTO) => void",
                    "resolved": "(vehicleInformation: VehicleLookupDTO) => void",
                    "references": {
                        "VehicleLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/vehicle-lookup/vehicle-lookup-dto",
                            "id": "src/global/types/generated/vehicle-lookup/vehicle-lookup-dto.ts::VehicleLookupDTO"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "showTrace": {
                "type": "boolean",
                "attribute": "show-trace",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "locale": {},
            "isError": {},
            "errorMessage": {},
            "isLoading": {},
            "vehicleLookup": {},
            "blazorRef": {},
            "activeTab": {},
            "showPrintBox": {},
            "tabAnimationLoading": {},
            "lastSuccessfulClaimResponse": {},
            "showClaimableItemPopover": {},
            "selectedClaimItem": {},
            "tabs": {},
            "popoverTarget": {},
            "popoverHeight": {},
            "popoverBodyContentHeight": {},
            "popoverContentFading": {},
            "popoverFadingOut": {},
            "showTraceModal": {},
            "traceModalFadingOut": {},
            "isLoadingTrace": {},
            "traceError": {},
            "traceHtml": {}
        };
    }
    static get methods() {
        return {
            "setMockData": {
                "complexType": {
                    "signature": "(newMockData: VehicleLookupMock) => Promise<void>",
                    "parameters": [{
                            "name": "newMockData",
                            "type": "{ [key: string]: VehicleLookupDTO; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "VehicleLookupMock": {
                            "location": "import",
                            "path": "~features/vehicle-lookup-component/types",
                            "id": "src/features/vehicle-lookup-component/types.ts::VehicleLookupMock"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "fetchVin": {
                "complexType": {
                    "signature": "(newData: VehicleLookupDTO | string, headers?: any) => Promise<void>",
                    "parameters": [{
                            "name": "newData",
                            "type": "string | VehicleLookupDTO",
                            "docs": ""
                        }, {
                            "name": "headers",
                            "type": "any",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "VehicleLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/vehicle-lookup/vehicle-lookup-dto",
                            "id": "src/global/types/generated/vehicle-lookup/vehicle-lookup-dto.ts::VehicleLookupDTO"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "setErrorMessage": {
                "complexType": {
                    "signature": "(message: ErrorKeys) => Promise<void>",
                    "parameters": [{
                            "name": "message",
                            "type": "\"noBaseUrl\" | \"invalidVin\" | \"vinNumberRequired\" | \"partNumberRequired\" | \"wrongResponseFormat\" | \"noPartsFound\" | \"noServiceAvailable\" | \"wrongFormStructure\" | \"wildCard\" | \"requestFailedPleaseTryAgainLater\"",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "ErrorKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::ErrorKeys"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "setBlazorRef": {
                "complexType": {
                    "signature": "(newBlazorRef: DotNetObjectReference) => Promise<void>",
                    "parameters": [{
                            "name": "newBlazorRef",
                            "type": "{ invokeMethodAsync: (methodName: string, ...args: any[]) => Promise<any>; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "DotNetObjectReference": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::DotNetObjectReference"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "openTrace": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "completeClaim": {
                "complexType": {
                    "signature": "(response: any) => Promise<void>",
                    "parameters": [{
                            "name": "response",
                            "type": "any",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "VehicleLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/vehicle-lookup/vehicle-lookup-dto",
                            "id": "src/global/types/generated/vehicle-lookup/vehicle-lookup-dto.ts::VehicleLookupDTO"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "claim": {
                "complexType": {
                    "signature": "(item: VehicleServiceItemDTO) => Promise<void>",
                    "parameters": [{
                            "name": "item",
                            "type": "{ group: VehicleServiceItemGroup; showDocumentUploader: boolean; warnings?: VehicleItemWarning[]; printUrl?: string; documentUploaderIsRequired: boolean; name: string; description: string; title: string; image: string; type: string; typeEnum: \"Free\" | \"Paid\"; activatedAt: string; expiresAt?: string; status: string; statusEnum: \"Pending\" | \"Processed\" | \"Expired\" | \"Cancelled\" | \"ActivationRequired\"; campaignID?: number; campaignUniqueReference: string; packageCode: string; cost?: number; claimDate?: string; modelCostID?: number; serviceItemID: string; paidServiceInvoiceLineID?: string; companyName: string; invoiceNumber: string; jobNumber: string; maximumMileage?: number; claimable: boolean; claimingMethodEnum: \"ClaimByScanningQRCode\" | \"ClaimByEnteringInvoiceAndJobNumber\"; vehicleInspectionID: string; vehicleInspectionTypeID: string; campaignVinEntryID: string; signature: string; signatureExpiry: string; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "VehicleServiceItemDTO": {
                            "location": "import",
                            "path": "~types/generated/vehicle-lookup/vehicle-service-item-dto",
                            "id": "src/global/types/generated/vehicle-lookup/vehicle-service-item-dto.ts::VehicleServiceItemDTO"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "changeLanguage"
            }, {
                "propName": "isLoading",
                "methodName": "onLoadingChange"
            }, {
                "propName": "vehicleLookup",
                "methodName": "onVehicleChange"
            }];
    }
}
VehicleClaimableItems.POPOVER_CLOSE_DELAY_MS = 200;
VehicleClaimableItems.POPOVER_FADE_OUT_MS = 500;
VehicleClaimableItems.POPOVER_CONTENT_FADE_MS = 150;
VehicleClaimableItems.TRACE_FADE_OUT_MS = 300;
