'use strict';

var index = require('./index-p7cvUYAE.js');
var utils$1 = require('./utils-CYONRFR6.js');
var parts = require('./parts-BXshb_S-.js');
var button = require('./button-CR9Rl1-o.js');
var skeleton = require('./skeleton-DvRCiQlA.js');
require('./event-types-YOY5TKUN.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var utils = require('./utils-BsnepLy6.js');
var eventTypes = require('./event-types-VgI-nT8p.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
require('./dinero-BwNN_k7x.js');
require('./Api-D9vOcUw4.js');
require('./config-state-BIgGhhe9.js');
require('./index-W-zoNiyM.js');
require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
require('./package-YyJzVqrh.js');

const makeUpdateDisputeResponse = ({ authToken, disputeId, service }) => async ({ payload, onSuccess, onError, final = () => { } }) => {
    var _a;
    try {
        const response = await service.updateDisputeResponse(disputeId, authToken, payload);
        if (!response.error) {
            onSuccess(response);
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};
const makeSubmitDisputeResponse = ({ authToken, disputeId, service }) => async ({ payload, onSuccess, onError, final = () => { } }) => {
    var _a;
    try {
        const response = await service.submitDisputeResponse(disputeId, authToken, payload);
        if (!response.error) {
            onSuccess(response);
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};
const makeCreateDisputeEvidence = ({ authToken, disputeId, service }) => async ({ payload, onSuccess, onError, final = () => { } }) => {
    var _a;
    try {
        const response = await service.createDisputeEvidence(disputeId, authToken, payload);
        if (!response.error) {
            onSuccess(response);
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};

const DisputeNotification = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.submitEvent = index.createEvent(this, "submit-event", 7);
    }
    acceptDispute() {
        makeSubmitDisputeResponse({
            disputeId: this.dispute.id,
            authToken: this.authToken,
            service: new eventTypes.DisputeService()
        })({
            payload: { forfeit: true },
            onSuccess: (response) => {
                this.submitEvent.emit({ response: response });
            },
            onError: ({ error, code, severity }) => {
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            },
        });
    }
    initiateRespondToDispute() {
        this.clickEvent.emit({ name: eventTypes.DisputeManagementClickActions.respondToDispute });
    }
    isDueDatePassed() {
        var _a;
        if (!((_a = this.dispute) === null || _a === void 0 ? void 0 : _a.due_date)) {
            return false;
        }
        // Fix for JavaScript Date object parsing
        // https://stackoverflow.com/a/31732581
        const dueDate = new Date(this.dispute.due_date.replace(/-/g, '/').replace(/T.+/, ''));
        const today = new Date();
        // Reset time to compare only dates
        today.setHours(0, 0, 0, 0);
        dueDate.setHours(0, 0, 0, 0);
        return dueDate < today;
    }
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        return (index.h("div", { key: '325018c414e82b5c1bc7d9c5aa444b5a9d4e83d6', class: "dispute-notification-root" }, this.isLoading && (index.h("div", { key: 'deffb8ef248e32962aca084a564e83aa5f222b0a', style: { marginBottom: '8px' } }, index.h(skeleton.Skeleton, { key: '6f6c630b3122b1b2fd480470f5df7683f19de612', height: '28px', width: '70%', styles: { marginBottom: '16px' } }), index.h(skeleton.Skeleton, { key: '11f46711fed1094496c64551f084351c08f598be', height: '18px', styles: { marginBottom: '8px' } }), index.h(skeleton.Skeleton, { key: 'fc7e2eac76e1cbc329147f3da39a8c28c51a7b6a', height: '18px', styles: { marginBottom: '8px' } }))), ((_a = this.dispute) === null || _a === void 0 ? void 0 : _a.needsResponse) && this.isDueDatePassed() && (index.h("div", { key: '0ef159acf9fe5b12dc0dcddab6b7583e5fc9a799', part: parts.text }, index.h("h1", { key: 'db263006990c5b4cf178f7f81650ad7602765532', class: "h4", part: parts.heading4 }, "The due date (", (_b = this.dispute) === null || _b === void 0 ? void 0 :
            _b.due_date, ") for this dispute has passed"), index.h("p", { key: '185c6f952ef46e3aec625cab73c943b3046ef6b4' }, "You can no longer submit evidence to counter this dispute."))), ((_c = this.dispute) === null || _c === void 0 ? void 0 : _c.needsResponse) && !this.isDueDatePassed() && (index.h("div", { key: 'd4536104addc500277fbde990b7b33ba8ff54c7e', part: parts.text }, index.h("h1", { key: '198138cc6541c0aeeae458e2de1e3ae0c695328d', class: "h4", part: parts.heading4 }, "This payment is disputed"), index.h("p", { key: '6902ce5e3e94ab7f71ee6d0c6a7604ef97f0e740' }, "The cardholder is disputing this payment. You may accept this dispute, or proceed to provide evidence in a counter dispute."), index.h("h2", { key: 'f49d1ac855365480edc61e0af117230e2f3dbe1f', class: "h5" }, "Dispute details"), index.h("div", { key: 'f3868a098dbc4a613d676b8580c053527f9d5fad', class: "d-table gap-2" }, index.h("div", { key: '7699bc619b652ffe1c77cf6e5e0dac967679b1e6', class: "d-table-row gap-2" }, index.h("span", { key: '9de67b45877120f54f724f1efe7b3f4d4b035d30', part: "detail-section-item-title", class: "fw-bold d-table-cell pe-4" }, "Amount"), index.h("span", { key: 'bfd79f86b5b81daf2a34f5874fcff03a05d1e64d', part: "detail-section-item-data", class: "flex-1 d-table-cell text-wrap" }, utils$1.formatCurrency((_d = this.dispute) === null || _d === void 0 ? void 0 : _d.amount))), index.h("div", { key: '0e57d56172859eb5857a1930cb837569157026d9', class: "d-table-row gap-2" }, index.h("span", { key: '0b615bd8f9a9add7d18d50be4f4f644707576de2', part: "detail-section-item-title", class: "fw-bold d-table-cell pe-4" }, "Reason"), index.h("span", { key: '46288c67be32fe2d95fea88f5b0148f22552a2c9', part: "detail-section-item-data", class: "flex-1 d-table-cell text-wrap" }, (_e = this.dispute) === null || _e === void 0 ? void 0 : _e.reason)), index.h("div", { key: 'c68280b0f36280804fb6231236d942174c189456', class: "d-table-row gap-2" }, index.h("span", { key: 'ed3f145aa0f2c949b80d7033e4ecb818a4a4fa68', part: "detail-section-item-title", class: "fw-bold d-table-cell pe-4" }, "Due Date"), index.h("span", { key: '4c4530acbc570fb13b5f53947714bd250ff99cab', part: "detail-section-item-data", class: "flex-1 d-table-cell text-wrap" }, (_f = this.dispute) === null || _f === void 0 ? void 0 : _f.due_date))), index.h("div", { key: '3244bb6bdbed2b4e28c479c2d4db2d0ae152f2f0', class: "d-flex gap-2 mt-4 justify-content-end" }, index.h(button.Button, { key: '3716a28cec93e70690ad96bfc0c5f3b7b56f8ecb', variant: "secondary", onClick: () => this.acceptDispute() }, "Accept dispute"), index.h(button.Button, { key: '7f326ed6f298c9f1091b160c63e386864329190e', variant: "primary", onClick: () => this.initiateRespondToDispute() }, "Counter dispute")))), ((_g = this.dispute) === null || _g === void 0 ? void 0 : _g.underReview) && (index.h("div", { key: 'd705ae48c1f30b904ac31bbdbab9e955868f51e1', part: parts.text }, index.h("h1", { key: '712cebef3699a8c2a97bcb69ae68e0b491090c88', class: "h4", part: parts.heading4 }, "This payment is disputed and under review"), index.h("p", { key: 'ca95b2c8bdc6083a3fbb1dd63c6bdaa4699ae2a7' }, "The cardholder is disputing this payment. A counter dispute has been submitted and is under review."))), ((_h = this.dispute) === null || _h === void 0 ? void 0 : _h.won) && (index.h("div", { key: 'c0cb4c8342aa4f022d76e95123a047b7b707f562', part: parts.text }, index.h("h1", { key: '797966d237d4b46eb1b880deb7fa21746f5b3b1e', class: "h4", part: parts.heading4 }, "This payment was disputed"), index.h("p", { key: '2f9eed1a5f34f772206112488af22aa8b35c07b6' }, "The cardholder disputed this payment and the card issuer has settled it in your favor."))), ((_j = this.dispute) === null || _j === void 0 ? void 0 : _j.lost) && (index.h("div", { key: '9a90af51218ed921e27519363995f12e29713bfd', part: parts.text }, index.h("h1", { key: '736ee5cf8f65d780d4812e24ea9050dcc0d109a4', class: "h4", part: parts.heading4 }, "This payment was disputed"), index.h("p", { key: '9ca83087b028e1078bcc2cd0b552e8f5379932d1' }, "The cardholder disputed this payment and the card issuer has settled it in their favor.")))));
    }
};

const DisputeResponse = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.stepCompleteEvent = index.createEvent(this, "complete-form-step-event", 7);
        this.submitEvent = index.createEvent(this, "submit-event", 7);
        this.errorMessage = null;
        this.disputeResponse = {};
        this.apiOrigin = "https://wc-proxy.justifi.ai";
        this.isLoading = false;
        this.documentList = [];
        this.documentErrors = {};
        this.currentStep = 0;
        this.componentStepMapping = [
            () => (index.h("product-or-service", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("customer-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("cancellation-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("refund-policy", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("duplicate-charge", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("electronic-evidence", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("shipping-details", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
            () => (index.h("additional-statement", { ref: (el) => (this.currentStepComponentRef = el), disputeResponse: this.disputeResponse, documentErrors: this.documentErrors })),
        ];
        this.saveData = async (formData, formStep) => {
            const hasFormData = Object.keys(formData).length;
            if (!hasFormData) {
                this.stepCompleteEvent.emit({ response: null, formStep: formStep });
                return;
            }
            if (this.isLastStep) {
                return this.submitDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.submitEvent.emit({ response: response });
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
            else {
                return this.updateDisputeResponse({
                    payload: formData,
                    onSuccess: (response) => {
                        this.disputeResponse = Object.assign({}, response.data);
                        this.stepCompleteEvent.emit({ response: response, formStep: formStep });
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            errorCode: code,
                            message: error,
                            severity,
                        });
                    },
                });
            }
        };
        this.initializeMakePresignedURLs = async () => {
            const presignedUrlPromises = this.documentList.map((document) => {
                return this.getPresignedFileUrl(document);
            });
            return await Promise.all(presignedUrlPromises);
        };
        this.initializeFileUploads = async () => {
            const uploadDocumentPromises = this.documentList.map((document) => {
                return this.uploadDocument(document);
            });
            return Promise.all(uploadDocumentPromises);
        };
        this.getPresignedFileUrl = async (document) => {
            return this.createDisputeEvidence({
                payload: {
                    file_name: document.file_name,
                    file_type: document.file_type,
                    dispute_evidence_type: document.dispute_evidence_type,
                },
                onSuccess: (response) => {
                    document.presignedUrl = response.data.presigned_url;
                },
                onError: ({ error, code, severity }) => {
                    const errors = { [document.dispute_evidence_type]: error };
                    this.documentErrors = Object.assign(Object.assign({}, this.documentErrors), errors);
                    this.errorEvent.emit({
                        errorCode: code,
                        message: error,
                        severity,
                    });
                },
            });
        };
        this.uploadDocument = async (document) => {
            const fileData = await document.getFileString();
            if (!document.presignedUrl) {
                throw new Error('Presigned URL is not set');
            }
            const response = await fetch(document.presignedUrl, {
                method: 'PUT',
                body: fileData,
            });
            return response;
        };
        this.handleSubmit = async (formData, documentList, formStep) => {
            this.isLoading = true;
            if (documentList.length) {
                this.documentErrors = {};
                this.documentList = documentList;
                await this.initializeMakePresignedURLs();
                const hasPresigningErrors = Object.keys(this.documentErrors).length;
                if (hasPresigningErrors) {
                    this.isLoading = false;
                    throw new Error('Could not presign all documents');
                }
                await this.initializeFileUploads();
            }
            await this.saveData(formData, formStep);
            this.isLoading = false;
        };
        this.onCancel = () => {
            this.clickEvent.emit({ name: eventTypes.DisputeManagementClickActions.cancelDispute });
        };
        this.onBack = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: eventTypes.DisputeManagementClickActions.previousStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep--;
            });
        };
        this.onNext = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: eventTypes.DisputeManagementClickActions.nextStep });
                await this.handleSubmit(formData, documentList, formStep);
                this.currentStep++;
            });
        };
        this.onSubmit = async () => {
            await this.currentStepComponentRef.validateAndSubmit(async (formData, documentList, formStep) => {
                this.clickEvent.emit({ name: eventTypes.DisputeManagementClickActions.submit });
                const submitData = Object.assign(Object.assign({}, formData), { forfeit: false });
                await this.handleSubmit(submitData, documentList, formStep);
            });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initializeDisputeServiceMethods();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    propChanged() {
        this.initializeDisputeServiceMethods();
    }
    initializeDisputeServiceMethods() {
        if (this.disputeId && this.authToken) {
            this.updateDisputeResponse = makeUpdateDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new eventTypes.DisputeService(),
            });
            this.createDisputeEvidence = makeCreateDisputeEvidence({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new eventTypes.DisputeService(),
            });
            this.submitDisputeResponse = makeSubmitDisputeResponse({
                disputeId: this.disputeId,
                authToken: this.authToken,
                service: new eventTypes.DisputeService(),
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    get currentStepComponent() {
        return this.componentStepMapping[this.currentStep]();
    }
    get isLastStep() {
        return this.currentStep === this.componentStepMapping.length - 1;
    }
    get isFirstStep() {
        return this.currentStep === 0;
    }
    render() {
        return (index.h("div", { key: '7f9c8d56cfb86cea73ab2f299b83ff0de28f5c3e', class: "dispute-response-root" }, index.h("div", { key: 'a805bf54df79453127557bf651c3d776a381241f', class: "row gy-3" }, index.h("div", { key: '2e6bc9cbe369e0ea5d200bc0934b4cad50f3c76f', class: "col-12" }, index.h("h1", { key: '9876e9c87c6dfb405e7bad46d64fdb40ad048142', class: "h4", part: parts.heading4 }, "Counter dispute")), index.h("div", { key: '045028232da5331c7041ad222c4e98364674ace3', class: "col-12" }, this.currentStepComponent), index.h("div", { key: '0455c4856a44340ce25c1c4c8f776abb197f919f', class: "col-12" }, index.h("div", { key: '5b990cc1d41b3a7152d727c941e9758ed70f75a1', class: "d-flex gap-2 mt-4 justify-content-end" }, this.isFirstStep ? (index.h(button.Button, { variant: "secondary", onClick: () => this.onCancel(), disabled: this.isLoading, isLoading: this.isLoading }, "Cancel")) : (index.h(button.Button, { variant: "secondary", onClick: () => this.onBack(), disabled: this.isLoading, isLoading: this.isLoading }, "Back")), this.isLastStep ? (index.h(button.Button, { variant: "primary", onClick: () => this.onSubmit(), disabled: this.isLoading, isLoading: this.isLoading }, "Submit Counter Dispute")) : (index.h(button.Button, { variant: "primary", onClick: () => this.onNext(), disabled: this.isLoading, isLoading: this.isLoading }, "Next")))))));
    }
    static get watchers() { return {
        "disputeId": ["propChanged"],
        "authToken": ["propChanged"]
    }; }
};

exports.dispute_notification = DisputeNotification;
exports.dispute_response = DisputeResponse;
